public static void main(String[] args) {
    AbstractApplicationContext context =
        new ClassPathXmlApplicationContext(
            "spring-configuration/serialization-spring-configuration.xml");
    Employee employee = (Employee) context.getBean("employee");

    // Employee employee = new Employee();//I don't need this line any more,
    // since I quickly set up a component-scan using Spring to auto wire
    // this employee bean for me, this is so cool! I feel so at home with
    // Spring dependency injection now! Praise the Lord!a
    employee.setName("Steve Sun");
    employee.setAge(26);
    employee.setAddress("1860 Charmeran Ave, San Jose, USA.");
    employee.setSSN(12345678);
    employee.setSalary(103000);

    try {
      FileOutputStream fos = new FileOutputStream(FILE_DIRECTORY);
      ObjectOutputStream ous = new ObjectOutputStream(fos);
      ous.writeObject(employee);
      ous.close();
      fos.close();
      System.out.println("Serialized data is saved in " + FILE_DIRECTORY + ".");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public static void main(String[] args) throws Exception {
   logger.debug("Starting application context.");
   new Main().initARP();
   AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
   ctx.getBean(TcpServer.class).start();
   // ctx.registerShutdownHook();
 }
Esempio n. 3
0
 public static void main(String[] args) {
   AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
   context.registerShutdownHook();
   Country country = context.getBean("country", Country.class);
   System.out.println(country.getCapital("india"));
   System.out.println(country.getCapital("spain"));
 }
Esempio n. 4
0
  @Before
  public void setUp() {
    testCopy.setBook(testBook);
    testCopy.setBookRate(BookCopy.BOOK_RATE_GOOD);
    testLoan = new Loan(testUser, testCopy, initDate, endDate);

    applicationContext = new ClassPathXmlApplicationContext("spring/spring-persistence-test.xml");
    txManager =
        (PlatformTransactionManager) applicationContext.getBean(PlatformTransactionManager.class);
    dao = (LoanDAO) applicationContext.getBean(LoanDAO.class);
    bookDao = (BookDAO) applicationContext.getBean(BookDAO.class);
    copyDao = (BookCopyDAO) applicationContext.getBean(BookCopyDAO.class);
    userDao = (UserDAO) applicationContext.getBean(UserDAO.class);

    TransactionTemplate tmpl = new TransactionTemplate(txManager);
    tmpl.execute(
        new TransactionCallbackWithoutResult() {
          @Override
          protected void doInTransactionWithoutResult(TransactionStatus status) {
            bookDao.saveOrUpdate(testBook);
            copyDao.saveOrUpdate(testCopy);
            userDao.saveOrUpdate(testUser);
          }
        });
  }
 /**
  * Interface method implementation. Closes all Spring application contexts that are maintained by
  * this BootstrapExtension
  *
  * @see org.trpr.platform.runtime.spi.bootstrapext.BootstrapExtension#destroy()
  */
 public void destroy() {
   for (AbstractApplicationContext appContext : ApplicationContextFactory.appContextMap.values()) {
     appContext.close();
     appContext = null;
   }
   ApplicationContextFactory.appContextMap.clear();
 }
Esempio n. 6
0
  public static void main(String args[]) {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    EmployeeService service = (EmployeeService) context.getBean("employeeService");

    /*
     * Create Employee1
     */
    Employee employee1 = new Employee();
    employee1.setName("Han Yenn");
    employee1.setJoiningDate(new LocalDate(2010, 10, 10));
    employee1.setSalary(new BigDecimal(10000));
    employee1.setSsn("ssn00000001");

    /*
     * Create Employee2
     */
    Employee employee2 = new Employee();
    employee2.setName("Dan Thomas");
    employee2.setJoiningDate(new LocalDate(2012, 11, 11));
    employee2.setSalary(new BigDecimal(20000));
    employee2.setSsn("ssn00000002");

    /*
     * Persist both Employees
     */
    service.saveEmployee(employee1);
    service.saveEmployee(employee2);

    /*
     * Get all employees list from database
     */
    List<Employee> employees = service.findAllEmployees();
    for (Employee emp : employees) {
      System.out.println(emp);
    }

    /*
     * delete an employee
     */
    service.deleteEmployeeBySsn("ssn00000002");

    /*
     * update an employee
     */

    Employee employee = service.findBySsn("ssn00000001");
    employee.setSalary(new BigDecimal(50000));
    service.updateEmployee(employee);

    /*
     * Get all employees list from database
     */
    List<Employee> employeeList = service.findAllEmployees();
    for (Employee emp : employeeList) {
      System.out.println(emp);
    }

    context.close();
  }
  /**
   * Allows to instantiate the selected {@link WebDriver} by given parameters. These parameters
   * should correspond existing {@link WebDriver} constructors
   *
   * @param supporteddriver the selected {@link WebDriver} representation
   * @param values they are used to launch {@link WebDriver}
   */
  public WebDriverEncapsulation(ESupportedDrivers supporteddriver, Object... values) {
    try {
      Class<? extends WebDriver> driverClass = supporteddriver.getUsingWebDriverClass();

      AbstractApplicationContext context =
          new AnnotationConfigApplicationContext(WebDriverBeanConfiguration.class);
      enclosedDriver =
          (RemoteWebDriver)
              context.getBean(
                  WebDriverBeanConfiguration.WEBDRIVER_BEAN,
                  context,
                  this,
                  destroyableObjects,
                  driverClass,
                  values);
      Log.message("Getting started with " + driverClass.getSimpleName());
      timeOut = getComponent(TimeOut.class);
      resetAccordingTo(configuration);
      this.instantiatedESupportedDriver = supporteddriver;

    } catch (Exception e) {
      Log.error(
          "Attempt to create a new web driver instance has been failed! " + e.getMessage(), e);
      destroy();
      throw new RuntimeException(e);
    }
  }
  public static void main(String[] args) {
    String[] files = {"src/spring.xml", "src/spring2.xml"};
    AbstractApplicationContext ctx = new FileSystemXmlApplicationContext(files);

    Flier flier01 = (Flier) ctx.getBean("flier01");
    System.out.println(flier01.getFlierName());
    System.out.println(flier01.getFlierID());

    ContactInfo inf = flier01.getContactInfo();
    System.out.println(inf.getEmailAddress());

    flier01.setLevel(Flier.Level.Gold);
    Segment seg01 = (Segment) ctx.getBean("seg01");
    System.out.println(seg01.getMiles());
    System.out.println("Segment number: " + seg01.getSegmentNumber());
    System.out.println("Segment miles: " + seg01.getMiles());

    flier01.addSegment(seg01);

    BonusCalc bc = (BonusCalc) ctx.getBean("calcBonus");
    int bonus = bc.calcBonus(flier01, seg01);
    System.out.println(bonus);

    AddressInfo ai = flier01.getHomeAddress();
    System.out.println(ai);

    ctx.close();
  }
  /**
   * Runs the Jetty Embedded DTS Web Service.
   *
   * @throws Exception if the Server fails to start
   */
  public void run() throws Exception {
    final AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext(
            new String[] {
              "/org/dataminx/dts/ws/application-context.xml",
              "/org/dataminx/dts/ws/embedded-jetty-context.xml"
            });
    ctx.registerShutdownHook();

    final Server server = (Server) ctx.getBean("jettyServer");

    ServletContext servletContext = null;

    for (final Handler handler : server.getHandlers()) {
      if (handler instanceof Context) {
        final Context context = (Context) handler;

        servletContext = context.getServletContext();
      }
    }

    final XmlWebApplicationContext wctx = new XmlWebApplicationContext();
    wctx.setParent(ctx);
    wctx.setConfigLocation("");
    wctx.setServletContext(servletContext);
    wctx.refresh();

    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wctx);

    server.start();
  }
Esempio n. 10
0
  public static void main(String[] args) {

    try (AbstractApplicationContext context = new AnnotationConfigApplicationContext(App.class)) {
      context.registerShutdownHook();

      context.getBean(SignalEmitter.class).emit();
    }
  }
 private static void initSessionFactory() {
   try {
     AbstractApplicationContext applicationContext =
         new ClassPathXmlApplicationContext("hibernate-config-test.xml");
     sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Esempio n. 12
0
 public static void inheritanceExample() {
   System.out.println("----inheritanceExample----");
   AbstractApplicationContext ctx =
       new ClassPathXmlApplicationContext("com/wilson/testlab/spring/b/bean/beans.xml");
   HelloWorld helloWorldChild = (HelloWorld) ctx.getBean("helloWorldChild");
   helloWorldChild.getMessage();
   helloWorldChild.getMessage2();
   helloWorldChild.getMessage3();
 }
 @Override
 public boolean appStart(IScope app) {
   log.debug("Starting BigBlueButton version " + version);
   IContext context = app.getContext();
   appCtx = (AbstractApplicationContext) context.getApplicationContext();
   appCtx.addApplicationListener(new ShutdownHookListener());
   appCtx.registerShutdownHook();
   return super.appStart(app);
 }
Esempio n. 14
0
  /** Run a checkpoint of the crawler */
  public synchronized String requestCrawlCheckpoint() throws IllegalStateException {
    if (isCheckpointing()) {
      throw new IllegalStateException("Checkpoint already running.");
    }

    // prevent redundant auto-checkpoints when crawler paused
    if (controller.isPaused()) {
      if (controller.getStatisticsTracker().getSnapshot().sameProgressAs(lastCheckpointSnapshot)) {
        LOGGER.info("no progress since last checkpoint; ignoring");
        System.err.println("no progress since last checkpoint; ignoring");
        return null;
      }
    }

    Map<String, Checkpointable> toCheckpoint = appCtx.getBeansOfType(Checkpointable.class);
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("checkpointing beans " + toCheckpoint);
    }

    checkpointInProgress = new Checkpoint();
    try {
      checkpointInProgress.generateFrom(getCheckpointsDir(), getNextCheckpointNumber());

      // pre (incl. acquire necessary locks)
      //            long startMs = System.currentTimeMillis();
      for (Checkpointable c : toCheckpoint.values()) {
        c.startCheckpoint(checkpointInProgress);
      }
      //            long duration = System.currentTimeMillis() - startMs;
      //            System.err.println("all startCheckpoint() completed in "+duration+"ms");

      // flush/write
      for (Checkpointable c : toCheckpoint.values()) {
        //                long doMs = System.currentTimeMillis();
        c.doCheckpoint(checkpointInProgress);
        //                long doDuration = System.currentTimeMillis() - doMs;
        //                System.err.println("doCheckpoint() "+c+" in "+doDuration+"ms");
      }
      checkpointInProgress.setSuccess(true);
      appCtx.publishEvent(new CheckpointSuccessEvent(this, checkpointInProgress));
    } catch (Exception e) {
      checkpointFailed(e);
    } finally {
      checkpointInProgress.writeValidity(controller.getStatisticsTracker().getProgressStamp());
      lastCheckpointSnapshot = controller.getStatisticsTracker().getSnapshot();
      // close (incl. release locks)
      for (Checkpointable c : toCheckpoint.values()) {
        c.finishCheckpoint(checkpointInProgress);
      }
    }

    this.nextCheckpointNumber++;
    LOGGER.info("finished checkpoint " + checkpointInProgress.getName());
    String nameToReport = checkpointInProgress.getSuccess() ? checkpointInProgress.getName() : null;
    this.checkpointInProgress = null;
    return nameToReport;
  }
Esempio n. 15
0
  private static void testJdbcDao() {
    System.out.println("=== JDBC DAO ===");

    AbstractApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"jdbc-dao-context.xml"});

    testDao((UserDao) context.getBean("userDao"));

    context.close();
  }
Esempio n. 16
0
  public static void beanPostProcessorExample() {

    System.out.println("----beanPostProcessorExample----");
    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext("com/wilson/testlab/spring/b/bean/beans2.xml");

    HelloWorld singletonObjA = (HelloWorld) ctx.getBean("helloWorldCallback");
    singletonObjA.getMessage();
    ((AbstractApplicationContext) ctx).registerShutdownHook();
  }
Esempio n. 17
0
 public static void main(String[] args) {
   AbstractApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
   EmployeeService service = context.getBean("service", EmployeeService.class);
   Employee employee = new Employee(new Date().getSeconds(), "ram", "*****@*****.**");
   service.addEmployee(employee);
   service.delEmployee(0);
   System.out.println(service.getAllEmployee().toString());
   System.out.println("End..............>>>>>>>>>>>>>");
   context.close();
 }
Esempio n. 18
0
  private static void testHiberJpaDao() {
    System.out.println("=== JPA+HIBERNATE DAO ===");

    AbstractApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"hibernate-dao-context.xml"});

    testDao((UserDao) context.getBean("userDao"));

    context.close();
  }
 @SuppressWarnings("resource")
 public static void main(String[] args) {
   AbstractApplicationContext applicationContext =
       new ClassPathXmlApplicationContext(
           new String[] {
             "classpath:com/penglecode/netty/rpc/example/applicationContext-rpc-server-cluster2.xml",
             "classpath:com/penglecode/netty/rpc/example/applicationContext-rpc-provider.xml"
           });
   applicationContext.start();
 }
  public static void main(String[] args) {

    AbstractApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("spring-test.xml");
    MongoDBMethods mongoDBMethods = applicationContext.getBean(MongoDBMethods.class);

    mongoDBMethods.save(ParseRule.COLLECTION_NAME, TestData.parseRule);

    applicationContext.close();
  }
 @Test
 public void stopAndRestartContext() {
   applicationContext.stop();
   applicationContext.start();
   this.input.send(new GenericMessage<String>("foo"));
   Message<?> message = this.output.receive(100);
   assertNotNull(message);
   assertEquals("foo: 1", message.getPayload());
   assertEquals(1, count);
 }
Esempio n. 22
0
 public static void main(String[] args) throws Exception {
   log.trace("main()");
   writePidFile();
   AbstractApplicationContext ctx = getContext();
   DGridProcessor driver = (DGridProcessor) ctx.getBean(DGridProcessor.NAME);
   Runtime.getRuntime().addShutdownHook(new ShutdownHook(driver));
   driver.init();
   provisionFactRunnable(ctx);
   Thread t = new Thread(driver);
   t.start();
 }
  /** @see DATAMONGO-331 */
  @Test
  public void readsReplicasWriteConcernCorrectly() {

    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext("namespace/db-factory-bean-custom-write-concern.xml");
    MongoDbFactory factory = ctx.getBean("second", MongoDbFactory.class);
    DB db = factory.getDb();

    assertThat(db.getWriteConcern(), is(WriteConcern.REPLICAS_SAFE));
    ctx.close();
  }
Esempio n. 24
0
  @Test
  public void testInsertAndGetId() {

    @SuppressWarnings("resource")
    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext(new String[] {"config/applicationContext.xml"});
    AdminDao userdao = (AdminDao) ctx.getBean("AdminDao");
    Admin user = new Admin();
    user.setAdminName("'why'");
    user.setAdminId("123");
    System.out.println(userdao.insertAndGetId(user));
  }
Esempio n. 25
0
  @Test
  public void testSaveAdmin() {

    @SuppressWarnings("resource")
    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext(new String[] {"config/applicationContext.xml"});
    AdminDao userdao = (AdminDao) ctx.getBean("AdminDao");
    Admin user = new Admin();
    user.setAdminName("'why'");
    user.setAdminId("123");
    userdao.save(user);
  }
  /**
   * Construct and load a new SubServicesBundle. Use default Spring application configuration to
   * build a new set of services.
   *
   * @param routerID
   * @return A new PathService instance from a new ApplicationContext.
   */
  private SubServicesBundle loadSubServices(String routerID) {
    /*
     * Create a parent context containing the bundle.
     */
    AbstractApplicationContext parentContext = new StaticApplicationContext();
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) parentContext;
    registerDataSource(routerID, parentContext, registry);
    parentContext.refresh();

    int retries = 0;
    SubServicesBundle retval = new SubServicesBundle();
    while (true) {
      try {
        /*
         * Create a new context to create a new path service, with all dependents services,
         * using the default application context definition. The creation of a new context
         * allow us to create new instances of service beans.
         */
        retval.context =
            new ClassPathXmlApplicationContext(subApplicationContextList, parentContext);
        AutowireCapableBeanFactory factory = retval.context.getAutowireCapableBeanFactory();
        retval.pathService = (PathService) factory.getBean("pathService", PathService.class);
        retval.patchService = (PatchService) factory.getBean("patchService", PatchService.class);
        break;

      } catch (BeanCreationException e) {
        /*
         * Copying a new graph should use an atomic copy, but for convenience if it is not,
         * we retry for a few times in case of truncated data before bailing out.
         *
         * The original StreamCorruptedException is buried within dozen of layers of other
         * exceptions, so we have to dig a bit (is this considered a hack?).
         */
        boolean streamCorrupted = false;
        Throwable t = e.getCause();
        while (t != null) {
          if (t instanceof StreamCorruptedException) {
            streamCorrupted = true;
            break;
          }
          t = t.getCause();
        }
        if (!streamCorrupted || retries++ > MAX_RETRIES) throw e;
        LOG.warn("Can't load " + routerID + " (" + e + "): retrying...");
        try {
          Thread.sleep(RETRY_INTERVAL);
        } catch (InterruptedException e1) {
        }
      }
    }
    return retval;
  }
Esempio n. 27
0
  public static void main(String[] args) {

    AbstractApplicationContext ctx =
        new GenericXmlApplicationContext("classpath:com/ppusari/spring/aop/xml/applicationCTX.xml");

    Student student = ctx.getBean("student", Student.class);
    student.getStudentInfo();

    Worker worker = ctx.getBean("worker", Worker.class);
    worker.getWorkerInfo();

    ctx.close();
  }
 @Override
 public synchronized void stop() {
   if (this.springContext instanceof AbstractApplicationContext) {
     AbstractApplicationContext ctx = (AbstractApplicationContext) this.springContext;
     try {
       if (ctx.isActive()) {
         ctx.stop();
       }
     } catch (Exception ex) {
     }
   }
   super.stop();
 }
  @Override
  public synchronized boolean start() {
    if (this.springContext instanceof AbstractApplicationContext) {
      AbstractApplicationContext ctx = (AbstractApplicationContext) this.springContext;
      try {
        if (!ctx.isActive()) {
          ctx.start();
        }
      } catch (Exception ex) {
      }
    }

    return super.start();
  }
  /**
   * @param args
   * @throws InterruptedException
   */
  public static void main(String[] args) throws InterruptedException {

    String conf = "spring.xml";
    AbstractApplicationContext context = new ClassPathXmlApplicationContext(conf);
    ConfigurableEnvironment configurableEnvironment = new StandardEnvironment();
    boolean testMode = false;

    if (args != null && args.length > 0) {
      if ("-test".equals(args[0])) {
        configurableEnvironment.setActiveProfiles("TEST");
        testMode = true;
      } else {
        configurableEnvironment.setActiveProfiles("PROD");
      }
    } else {
      configurableEnvironment.setActiveProfiles("PROD");
    }
    context.setEnvironment(configurableEnvironment);

    PropertyConfigurator.configure("resources/log4j.properties");

    logger.info("Starting launcher...");

    int iteration = 0;

    Launcher launcher = context.getBean("launcher", Launcher.class);

    while (true) {

      iteration++;

      logger.info("Iteration #" + iteration + " at " + new Date());

      logger.info(" Launching zezo automatic routing...");
      launcher.runZezoAutoRouting(testMode);

      /*
       * logger.info(" Launching waypoints..."); launcher.runWaypoints();
       *
       * logger.info(" Launching speed regulation...");
       * launcher.speedRegulation();
       */

      Date nextIteration = getNextIteration();
      long msToSleep = getSecondRemainingBefore(nextIteration);
      logger.info("Waiting for next iteration at " + nextIteration + "\n\n\n");
      Thread.sleep(msToSleep);
    }
  }