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:edu.mayo.cts2.uriresolver.dao.DAOUtiltities.java

public static DataSource createInMemoryDatabase(UriDAO uriDAO) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

    // createDatabase in memory
    logger.info("Creating an in memory database");
    DataSource ds = (DataSource) context.getBean("h2DataSource");
    context.close();//from  w w w .j a  va  2s . co m

    int connectionCode = uriDAO.checkDataSource(ds);

    importMySQLDataToH2Database(ds);

    if (connectionCode != 0) {
        logger.error("Unable to create in memory database.  Cannot continue.");
        return null;
    }

    return ds;
}

From source file:org.activiti.crystalball.simulator.GenerateProcessEngineState.java

private static void generateLiveDB() throws InterruptedException {

    RepositoryService repositoryService;
    IdentityService identityService;//from   w ww . j a  v  a2s . c  o m
    ProcessEngine processEngine;
    String LIVE_DB = TEMP_DIR + "/live-SimulateBottleneckTest";

    String previousLiveDB = System.getProperty("liveDB");
    System.setProperty("liveDB", LIVE_DB);

    // delete previous DB instalation and set property to point to the current file
    File prevDB = new File(LIVE_DB + ".h2.db");

    if (prevDB.exists())
        prevDB.delete();
    prevDB = null;

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");

    repositoryService = appContext.getBean(RepositoryService.class);

    identityService = appContext.getBean(IdentityService.class);
    processEngine = appContext.getBean(ProcessEngine.class);

    // deploy processes
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/ParallelUserTasksProcess.bpmn").deploy();

    // init identity service
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveGroup(identityService.newGroup("Group2"));
    identityService.saveGroup(identityService.newGroup("Group3"));
    identityService.saveGroup(identityService.newGroup("Group4"));
    identityService.saveUser(identityService.newUser("user1"));
    identityService.saveUser(identityService.newUser("user2"));
    identityService.saveUser(identityService.newUser("user3"));
    identityService.saveUser(identityService.newUser("user4"));

    identityService.createMembership("user1", "Group1");
    identityService.createMembership("user2", "Group2");
    identityService.createMembership("user3", "Group3");
    identityService.createMembership("user4", "Group4");
    identityService.createUserQuery().list();

    processEngine.close();

    appContext.close();

    if (previousLiveDB != null)
        System.setProperty("liveDB", previousLiveDB);
    else
        System.setProperty("liveDB", "");
}

From source file:org.activiti.crystalball.simulator.GenerateProcessEngineState.java

private static void generateBasicEngine() throws InterruptedException {
    String PROCESS_KEY = "threetasksprocess";
    RepositoryService repositoryService;
    RuntimeService runtimeService;//from  w  w  w .  j a  v a2 s . c  o m
    TaskService taskService;
    IdentityService identityService;
    ProcessEngine processEngine;
    String liveDB = TEMP_DIR + "/BasicSimulation";

    // delete previous DB instalation and set property to point to the current file
    File prevDB = new File(liveDB + ".h2.db");

    String previousLiveDB = System.getProperty("liveDB");

    System.setProperty("liveDB", liveDB);
    if (prevDB.exists())
        prevDB.delete();
    prevDB = null;

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");

    repositoryService = appContext.getBean(RepositoryService.class);
    runtimeService = appContext.getBean(RuntimeService.class);
    taskService = appContext.getBean(TaskService.class);
    identityService = appContext.getBean(IdentityService.class);
    processEngine = appContext.getBean(ProcessEngine.class);

    // deploy processes
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/ThreeTasksProcess.bpmn").deploy();

    // init identity service
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveGroup(identityService.newGroup("Group2"));
    identityService.saveUser(identityService.newUser("user1"));
    identityService.saveUser(identityService.newUser("user2"));

    identityService.createMembership("user1", "Group1");
    identityService.createMembership("user2", "Group2");

    // start processes 
    Calendar calendar = Calendar.getInstance();
    calendar.set(2012, 11, 7, 18, 1, 00);
    Date dueDateFormal = calendar.getTime();
    calendar.set(2012, 11, 7, 18, 1, 30);
    Date dueDateValue = calendar.getTime();
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("dueDateFormal", dueDateFormal);
    variables.put("dueDateValue", dueDateValue);

    for (int i = 0; i < 10; i++) {
        runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-" + i, variables);
    }

    // put first 5 tasks to the next node
    List<Task> taskList = taskService.createTaskQuery().taskCandidateUser("user1").list();
    for (int i = 0; i < 5; i++) {
        Task t = taskList.get(i);
        taskService.claim(t.getId(), "user1");
    }

    // wait some time  to have some data in history 
    Thread.sleep(500);

    // complete these tasks
    for (int i = 0; i < 5; i++) {
        Task t = taskList.get(i);
        taskService.complete(t.getId());
    }

    processEngine.close();

    appContext.close();

    if (previousLiveDB != null)
        System.setProperty("liveDB", previousLiveDB);
    else
        System.setProperty("liveDB", "");

}

From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java

@BeforeClass
public static void init() throws IOException {
    initFiles();// ww w.  j a va 2  s.  c  om

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
            "depositClientContext.xml", "classpath*:org/dataconservancy/config/applicationContext.xml" });

    client = (HttpClient) appContext.getBean("httpClient");
}

From source file:com.nokia.dempsy.spring.RunAppInVm.java

public static void run(String[] args) throws Throwable {
    //======================================================
    // Handle all of the options.
    String appCtxFilename = System.getProperty(appdefParam);
    if (appCtxFilename == null || appCtxFilename.length() == 0) {
        //         usage("the java vm option \"-D" + appdefParam + "\" wasn't specified.");
        String application = System.getProperty(applicationParam);
        if (application == null || application.length() == 0)
            usage("the java vm option \"-D" + appdefParam + "\" or the java vm option \"-D" + applicationParam
                    + "\" wasn't specified.");
        appCtxFilename = "DempsyApplicationContext-" + application + ".xml";
    }//w ww .  j a  v  a  2s . co m
    //======================================================

    String contextFile = "classpath:Dempsy-localVm.xml";
    ClassPathXmlApplicationContext context = null;
    try {
        // Initialize Spring
        context = new ClassPathXmlApplicationContext(new String[] { appCtxFilename, contextFile });
        context.registerShutdownHook();
    } catch (Throwable e) {
        logger.error(MarkerFactory.getMarker("FATAL"), "Failed to start the application ", e);
        throw e;
    }
    if (context != null) {
        try {
            context.getBean(Dempsy.class).waitToBeStopped();
        } catch (InterruptedException e) {
            logger.error("Interrupted . . . ", e);
        } finally {
            context.stop();
        }

        logger.info("Shut down dempsy appliction " + appCtxFilename + ", bye!");
    }
}

From source file:org.string_db.psicquic.index.StringdbSolrBasedPsicquicRestServiceITCase.java

@BeforeClass
public static void setupSolrPsicquicService() throws Exception {
    // index data to be hosted by PSICQUIC
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "/META-INF/beans.spring.test.xml", "classpath*:/META-INF/psicquic-spring.xml",
                    "/META-INF/psicquic-indexing-spring-test.xml" });
    service = (StringdbSolrBasedPsicquicRestService) context.getBean("stringdbSolrBasedPsicquicRestService");

    // Start a jetty server to host the solr index
    solrJettyRunner = new SolrJettyRunner();
    solrJettyRunner.start();// ww w.  ja  v a  2s . c o  m

    SolrMitabIndexer indexer = (SolrMitabIndexer) context.getBean("solrMitabIndexer");
    indexer.startJob("mitabIndexNegativeJob");

    HttpSolrServer solrServer = solrJettyRunner.getSolrServer();
    Assert.assertEquals(4L, solrServer.query(new SolrQuery("*:*")).getResults().getNumFound());
}

From source file:fr.gael.dhus.DHuS.java

/** Starts the DHuS (starts Tomcat, creates the Spring application context. */
public static void start() {
    // Transfer System.err in logger
    System.setErr(new PrintStream(new LoggingOutputStream(LOGGER), true));

    String version = DHuS.class.getPackage().getImplementationVersion();

    // Force ehcache not to call home
    System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");
    System.setProperty("user.timezone", "UTC");
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    System.setProperty("fr.gael.dhus.version", version == null ? "dev" : version);

    if (!SystemService.restore()) {
        LOGGER.error("Cannot run system restoration.");
        LOGGER.error("Check the restoration file \"" + SystemService.RESTORATION_PROPERTIES
                + "\" from the current directory.");
        System.exit(1);/*from  w ww .j a  va2 s . c  o  m*/
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            if ((server != null) && server.isRunning()) {
                try {
                    server.stop();
                } catch (TomcatException e) {
                    e.printStackTrace();
                }
            }
        }
    }));

    // Always add JMSAppender
    //Logger rootLogger = LogManager.getRootLogger ();
    //org.apache.logging.log4j.core.Logger coreLogger =
    //(org.apache.logging.log4j.core.Logger)rootLogger;
    //JMSAppender jmsAppender = JMSAppender.createAppender ();
    //coreLogger.addAppender (jmsAppender);
    try {
        // Activates the resolver for Drb
        DrbFactoryResolver.setMetadataResolver(new DrbCortexMetadataResolver(DrbCortexModel.getDefaultModel()));
    } catch (IOException e) {
        LOGGER.error("Resolver cannot be handled.");
        //logger.error (new Message(MessageType.SYSTEM,
        //"Resolver cannot be handled."));
    }

    LOGGER.info("Launching Data Hub Service...");
    //logger.info (new Message(MessageType.SYSTEM,
    //"Loading Data Hub Service..."));

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:fr/gael/dhus/spring/dhus-core-context.xml");
    context.registerShutdownHook();

    // Registers ContextClosedEvent listeners to properly save states before
    // the Spring context is destroyed.
    ApplicationListener sync_sv = context.getBean(ISynchronizerService.class);
    context.addApplicationListener(sync_sv);

    // Initialize Database Incoming folder
    IncomingManager incoming_manager = (IncomingManager) context.getBean("incomingManager");
    incoming_manager.initIncoming();

    // Initialize DHuS loggers
    //jmsAppender.cleanWaitingLogs ();
    //logger.info (new Message(MessageType.SYSTEM, "DHuS Started"));
    try {
        //ftp = xml.getBean (FtpServer.class);
        //ftp.start ();

        server = ApplicationContextProvider.getBean(TomcatServer.class);
        server.init();

        LOGGER.info("Starting server " + server.getClass() + "...");
        //logger.info (new Message(MessageType.SYSTEM, "Starting server..."));
        server.start();
        //logger.info (new Message(MessageType.SYSTEM, "Server started."));

        LOGGER.info("Server started.");

        // Initialises SolrDAO
        SolrDao solr_dao = (SolrDao) context.getBean("solrDao");
        solr_dao.initServerStarted();

        Map<String, WebApplication> webapps = context.getBeansOfType(WebApplication.class);
        for (String beanName : webapps.keySet()) {
            server.install(webapps.get(beanName));
        }

        fr.gael.dhus.server.http.web.WebApplication.installAll(server);
        WebServlet.installAll(server);
        WebPostProcess.launchAll();

        LOGGER.info("Server is ready...");
        started = true;

        //InitializableComponent.initializeAll ();
        //logger.info (new Message(MessageType.SYSTEM, "Server is ready..."));
        server.await();
    } catch (Exception e) {
        LOGGER.error("Cannot start system.", e);
        //logger.error (new Message(MessageType.SYSTEM, "Cannot start DHuS."), e);
        //ftp.stop ();
        System.exit(1);
    }
}

From source file:com.nokia.dempsy.spring.RunNode.java

public static void run(String[] args) throws Throwable {
    //======================================================
    // Handle all of the options.

    String application = System.getProperty(applicationParam);
    if (application == null || application.length() == 0)
        usage("the java vm option \"-D" + applicationParam + "\" wasn't specified.");

    String[] clusterIdParts = application.split(":");
    if (clusterIdParts.length != 2)
        usage("invalid format for the -Dcluster option. It should be a clusterid of the form \"applicationName:clusterName.\"");

    System.setProperty("application", clusterIdParts[0]);
    System.setProperty("cluster", clusterIdParts[1]);

    String appCtxFilename = System.getProperty(appdefParam);
    if (appCtxFilename == null || appCtxFilename.length() == 0) {
        //         usage("the java vm option \"-D" + appdefParam + "\" wasn't specified.");
        appCtxFilename = "DempsyApplicationContext-" + clusterIdParts[0] + ".xml";
    }//from   w w  w  .  ja v  a2  s.co  m

    String zkConnect = System.getProperty(zk_connectParam);
    if (zkConnect == null || zkConnect.length() == 0)
        usage("the java vm option \"-D" + zk_connectParam + "\" wasn't specified.");

    String zkTimeout = System.getProperty(zk_timeoutParam);
    if (zkTimeout == null || zkTimeout.length() == 0)
        System.setProperty(zk_timeoutParam, zk_timeoutDefault);

    String totalSlots = System.getProperty(total_slots_per_clusterParam);
    if (totalSlots == null || totalSlots.length() == 0)
        System.setProperty(total_slots_per_clusterParam, total_slots_per_clusterDefault);

    String minNodes = System.getProperty(min_num_nodes_per_clusterParam);
    if (minNodes == null || minNodes.length() == 0)
        System.setProperty(min_num_nodes_per_clusterParam, min_num_nodes_per_clusterDefault);
    //======================================================

    String contextFile = "classpath:Dempsy-distributed.xml";
    ClassPathXmlApplicationContext context = null;
    try {
        // Initialize Spring
        context = new ClassPathXmlApplicationContext(new String[] { appCtxFilename, contextFile });
        context.registerShutdownHook();
    } catch (Throwable e) {
        logger.error(MarkerFactory.getMarker("FATAL"), "Failed to start the application ", e);
        throw e;
    }
    if (context != null) {
        try {
            context.getBean(Dempsy.class).waitToBeStopped();
        } catch (InterruptedException e) {
            logger.error("Interrupted . . . ", e);
        } finally {
            context.stop();
        }

        logger.info("Shut down dempsy appliction " + appCtxFilename + "-" + application + ", bye!");
    }
}

From source file:org.activiti.crystalball.simulator.GenerateProcessEngineState.java

private static void generatePlaybackOriginal() throws InterruptedException, IOException {
    String PROCESS_KEY = "playback";
    RepositoryService repositoryService;
    RuntimeService runtimeService;/*w  ww . j ava 2s  . c o m*/
    TaskService taskService;
    IdentityService identityService;
    HistoryService historyService;
    ProcessEngine processEngine;
    String liveDB = TEMP_DIR + "/Playback";

    // delete previous DB instalation and set property to point to the current file
    File prevDB = new File(liveDB + ".h2.db");

    String previousLiveDB = System.getProperty("liveDB");

    System.setProperty("liveDB", liveDB);
    if (prevDB.exists())
        prevDB.delete();
    prevDB = null;

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");
    Calendar calendar = Calendar.getInstance();
    calendar.set(2013, 01, 25, 14, 30, 00);
    ClockUtil.setCurrentTime(calendar.getTime());

    repositoryService = appContext.getBean(RepositoryService.class);
    runtimeService = appContext.getBean(RuntimeService.class);
    taskService = appContext.getBean(TaskService.class);
    identityService = appContext.getBean(IdentityService.class);
    historyService = appContext.getBean(HistoryService.class);

    processEngine = appContext.getBean(ProcessEngine.class);

    // deploy processes
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/Playback.bpmn").deploy();

    // init identity service
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveUser(identityService.newUser("user1"));

    identityService.createMembership("user1", "Group1");

    // start processes 
    Map<String, Object> variables2 = new HashMap<String, Object>();
    variables2.put("x", 3);
    Map<String, Object> variables1 = new HashMap<String, Object>();
    variables1.put("x", 1);
    Map<String, Object> variables0 = new HashMap<String, Object>();
    variables0.put("x", 0);

    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-1",
            variables0);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-2",
            variables1);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-3", variables0);

    // put first 5 tasks to the next node
    List<Task> taskList = taskService.createTaskQuery().taskCandidateUser("user1").list();
    for (Task t : taskList) {
        taskService.claim(t.getId(), "user1");
    }

    // complete these tasks
    for (Task t : taskList) {
        // wait some time  to have some data in history 
        calendar.add(Calendar.SECOND, 1);
        ClockUtil.setCurrentTime(calendar.getTime());
        // complete task
        taskService.complete(t.getId(), variables2);
    }

    // audit trail images generator
    AuditTrailProcessDiagramGenerator generator = new AuditTrailProcessDiagramGenerator();
    generator.setHistoryService(historyService);
    generator.setRepositoryService((RepositoryServiceImpl) repositoryService);
    generator.setWriteUpdates(true);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance1.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail1.png"));

    params.clear();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance2.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail2.png"));

    processEngine.close();

    appContext.close();

    if (previousLiveDB != null)
        System.setProperty("liveDB", previousLiveDB);
    else
        System.setProperty("liveDB", "");

}

From source file:com.bt.aloha.batchtest.PerformanceBatchTest.java

private static int[] getInitParams() {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "batchTestApplicationContext.xml");
    PerformanceBatchTest t = (PerformanceBatchTest) applicationContext.getBean("performanceBatchTestBean");
    PerformanceMeasurmentDao dao = (PerformanceMeasurmentDao) applicationContext
            .getBean("performanceMeasurementDaoBean");
    long runId = dao.generateId();
    int jainPoolStart = t.getInitialJainPoolSize();
    int jainPoolMax = t.getMaxJainPoolSize();
    int jainPoolInc = t.getJainPoolSizeIncrement();
    int sssPoolStart = t.getInitialSssPoolSize();
    int sssPoolMax = t.getMaxSssPoolSize();
    int sssPoolInc = t.getSssPoolSizeIncrement();
    int start = t.getNumberOfInitialConcurrentStarts();
    int max = t.getNumberOfMaxConcurrentStarts();
    int inc = t.getNumberOfConcurrentStartsIncrements();
    applicationContext.destroy();//w  ww  .  jav a 2s. co  m

    return new int[] { (int) runId, jainPoolStart, jainPoolMax, jainPoolInc, sssPoolStart, sssPoolMax,
            sssPoolInc, start, max, inc };
}