Ejemplo n.º 1
0
  @Test
  public void testCreateQueueEndpoint() throws Exception {
    JmsEndpointComponent component = new JmsEndpointComponent();

    reset(applicationContext);
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(connectionFactory)
        .once();
    replay(applicationContext);

    Endpoint endpoint = component.createEndpoint("jms:queuename", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);

    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(), "queuename");
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().isPubSubDomain(), false);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getConnectionFactory(),
        connectionFactory);
    Assert.assertNull(((JmsEndpoint) endpoint).getEndpointConfiguration().getDestination());
    Assert.assertEquals(((JmsEndpoint) endpoint).getEndpointConfiguration().getTimeout(), 5000L);

    verify(applicationContext);
  }
  @Test
  public void getLastModified() throws Exception {
    Resource templateResource = new Template();
    long lastModified = factory.getResource("/templates/test.vm").lastModified();

    // 资源/templates/test.vm支持lastModified
    templateResource.setName("/test.vm");
    assertEquals(lastModified, velocityLoader.getLastModified(templateResource));

    // 资源/templates/notExist.vm不存在,返回0
    templateResource.setName("/notExist.vm");
    assertEquals(0, velocityLoader.getLastModified(templateResource));

    // 资源/templates/test2.vm存在,但不支持lastModified,返回0
    templateResource.setName("/test2.vm");
    assertEquals(0, factory.getResource("/templates/test2.vm").lastModified());
    assertEquals(0, velocityLoader.getLastModified(templateResource));

    // 模板名为空
    templateResource.setName(null);

    try {
      velocityLoader.getLastModified(templateResource);
      fail();
    } catch (org.apache.velocity.exception.ResourceNotFoundException e) {
      assertThat(e, exception("Need to specify a template name"));
    }
  }
  @Test
  public void withHeaderMapperStandardAndCustomHeaders() {
    AmqpInboundChannelAdapter adapter =
        context.getBean(
            "withHeaderMapperStandardAndCustomHeaders", AmqpInboundChannelAdapter.class);

    AbstractMessageListenerContainer mlc =
        TestUtils.getPropertyValue(
            adapter, "messageListenerContainer", AbstractMessageListenerContainer.class);
    MessageListener listener =
        TestUtils.getPropertyValue(mlc, "messageListener", MessageListener.class);
    MessageProperties amqpProperties = new MessageProperties();
    amqpProperties.setAppId("test.appId");
    amqpProperties.setClusterId("test.clusterId");
    amqpProperties.setContentEncoding("test.contentEncoding");
    amqpProperties.setContentLength(99L);
    amqpProperties.setContentType("test.contentType");
    amqpProperties.setHeader("foo", "foo");
    amqpProperties.setHeader("bar", "bar");
    Message amqpMessage = new Message("hello".getBytes(), amqpProperties);
    listener.onMessage(amqpMessage);
    QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class);
    org.springframework.integration.Message<?> siMessage = requestChannel.receive(0);
    assertEquals("foo", siMessage.getHeaders().get("foo"));
    assertNull(siMessage.getHeaders().get("bar"));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE));
  }
Ejemplo n.º 4
0
  @Scope("session")
  @RequestMapping(value = "/connect_human_company", method = RequestMethod.GET)
  public ModelAndView connectHumanCompany(HttpServletRequest request) {

    ModelAndView model = new ModelAndView("searchByCompany");
    try {

      ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
      CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
      CompanyDAO companyDAO = (CompanyDAO) context.getBean("companyDAO");

      int ID = Integer.parseInt(request.getParameter("campaignID"));
      int UserID = Integer.parseInt(request.getParameter("customerID"));

      HashMap<String, String> HashMap = new HashMap<String, String>();
      HashMap.put("ID", Integer.toString(ID));

      String sql = "UPDATE companies SET Count = Count -1 WHERE ID = " + ID;

      companyDAO.update(sql);

      sql = "UPDATE customer SET Assigned = '" + ID + "' WHERE CUST_ID = " + UserID;

      companyDAO.update(sql);

    } catch (Throwable q) {
      return model;
    }
    return model;
  }
Ejemplo n.º 5
0
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   ApplicationContext app = new ClassPathXmlApplicationContext("app.xml");
   MemberDAO dao = (MemberDAO) app.getBean("dao");
   /*Scanner scan=new Scanner(System.in);
   System.out.print("번호:");
   int no=scan.nextInt();
   dao.delete(no);
   System.out.println("삭제 완료");*/
   /*String name=scan.next();
   List<MemberVO> list=dao.memberFindData(name);
   for(MemberVO vo:list)
   {
   	System.out.println(vo.getNo()+" "
   			+vo.getName()+" "
   			+vo.getTel()+" "
   			+vo.getAddr());
   }*/
   MemberVO vo = new MemberVO();
   vo.setNo(2);
   vo.setName("박문식");
   vo.setTel("5555-5555");
   vo.setAddr("제주");
   dao.update(vo);
   System.out.println("데이터 수정 완료");
 }
  /**
   * Optionally accepts 1 argument. If the argument evaluates to true ({@link
   * Boolean#parseBoolean(String)}, the main method will NOT run the SQL statements in the
   * "destroyDdl" Resource.
   *
   * @param args
   */
  public static void main(String[] args) throws Exception {
    LOG.info("loading applicationContext: " + CONFIG);
    ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG);

    boolean firstRun = false;
    if (args.length == 1) {
      firstRun = Boolean.parseBoolean(args[0]);
    }
    InitializeSchedulingAssistantDatabase init = new InitializeSchedulingAssistantDatabase();
    init.setDataSource((DataSource) context.getBean("dataSource"));

    if (!firstRun) {
      Resource destroyDdl = (Resource) context.getBean("destroyDdl");
      if (null != destroyDdl) {
        String destroySql = IOUtils.toString(destroyDdl.getInputStream());
        init.executeDdl(destroySql);
        LOG.warn("existing tables removed");
      }
    }

    Resource createDdl = (Resource) context.getBean("createDdl");
    String createSql = IOUtils.toString(createDdl.getInputStream());

    init.executeDdl(createSql);
    LOG.info("database initialization complete");
  }
Ejemplo n.º 7
0
  @Scope("session")
  @RequestMapping(
      value = {"/search"},
      method = RequestMethod.GET)
  public String dashboard(
      Locale locale, Model model, HttpServletRequest request, HttpSession httpSession) {

    try {

      ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
      CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

      Map<Integer, HashMap<String, String>> ResultMap =
          new HashMap<Integer, HashMap<String, String>>();
      ResultMap =
          customerDAO.SQLquery(
              "SELECT companies.*,  NameIndustry FROM companies LEFT JOIN industry"
                  + " ON companies.Industry = industry.ID ");
      System.out.println(ResultMap);

      Map<Integer, HashMap<String, String>> ResultIndustry =
          new HashMap<Integer, HashMap<String, String>>();
      ResultIndustry = customerDAO.SQLquery("SELECT * FROM industry");

      model.addAttribute("ResultMap", ResultMap);
      model.addAttribute("ResultIndustry", ResultIndustry);

      return "search";
    } catch (Throwable t) {

      System.out.println(t);
      return "search";
    }
  }
Ejemplo n.º 8
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 필터로 대체한다.
    // request.setCharacterEncoding("UTF-8");

    ApplicationContext context =
        (ApplicationContext) this.getServletContext().getAttribute("beanContainer");

    BoardDao boardDao = (BoardDao) context.getBean("boardDao");

    Board board = new Board();
    board.setNo(Integer.parseInt(request.getParameter("no")));
    board.setTitle(request.getParameter("title"));
    board.setContent(request.getParameter("content"));
    board.setPassword(request.getParameter("password"));

    try {
      boardDao.update(board);
    } catch (Exception e) {
      RequestDispatcher rd = request.getRequestDispatcher("/error");

      // ServletRequest에 전달할 객체를 저장한다.
      request.setAttribute("error", e);

      rd.forward(request, response);
      return;
    }
    response.sendRedirect("list.do");
  }
Ejemplo n.º 9
0
  @Test
  public void getPagingListTest() throws Exception {
    //        String url =
    //               "http://employeeservice.hzfh.com:8080/service-employee/empCompilePlan";
    //		 HessianProxyFactory factory = new HessianProxyFactory();
    //        EmpCompilePlanService empCompilePlanService =
    // (EmpCompilePlanService)factory.create(EmpCompilePlanService.class, url);
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    EmpCompilePlanService empCompilePlanService =
        (EmpCompilePlanService) context.getBean("empCompilePlanService");

    EmpCompilePlanCondition empCompilePlanCondition = new EmpCompilePlanCondition();
    // productCondition.setId(1);
    empCompilePlanCondition.setPageIndex(1);
    empCompilePlanCondition.setPageSize(4);
    empCompilePlanCondition.setTotalCount(9);

    List<SortItem> sortItemList = new ArrayList<SortItem>();
    SortItem sortItem1 = new SortItem();
    sortItem1.setSortFeild("id");
    sortItem1.setSortType(SortType.DESC);
    sortItemList.add(sortItem1);
    empCompilePlanCondition.setSortItemList(sortItemList);

    // empCompilePlanCondition.setByPosition(2);
    // empCompilePlanCondition.setByYear(2015);
    PagedList<EmpCompilePlan> empCompilePlanList =
        empCompilePlanService.getPagingList(empCompilePlanCondition);
    System.out.println("getPagingListTest");
    for (EmpCompilePlan empCompilePlan : empCompilePlanList.getResultList()) {
      System.out.println(empCompilePlan.getId() + "," + empCompilePlan.getYear());
    }
  }
Ejemplo n.º 10
0
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beans.xml");

    BusinessBean business = (BusinessBean) context.getBean("businessBean");

    business.save();
  }
Ejemplo n.º 11
0
  public static void main(String[] args) {

    // 01. Basic usage
    //  Phone phone = new Phone();

    // 02. Injection with Constructor
    // Phone phone = new Phone(new A9X());

    // 03. Injection with Setter
    // Phone phone = new Phone();
    // phone.setCpu(new A9X());

    // 04. Injection with Spring Framework via XML [Maintenance]
    ApplicationContext context = new FileSystemXmlApplicationContext("dependencies.xml");
    Phone phone;

    phone = context.getBean("galaxy", Phone.class);
    display(phone);

    phone = context.getBean("iPhone", Phone.class);
    display(phone);

    // 05. Injection with Spring Framework via @AutoWired
    //     Strategy : Type -> Name
    phone = context.getBean("mi", Phone.class);
    display(phone);

    // 06. Injection with Javax via @Resource [Java Standard]
    //     Strategy : Name -> Type
    phone = context.getBean("prototype", Phone.class);
    display(phone);

    System.out.println("======================================================================");
  }
  @Override
  public ThreadPoolRequestReplicator getObject() throws Exception {
    if (replicator == null && nifiProperties.isNode()) {
      final EventReporter eventReporter =
          applicationContext.getBean("eventReporter", EventReporter.class);
      final ClusterCoordinator clusterCoordinator =
          applicationContext.getBean("clusterCoordinator", ClusterCoordinator.class);
      final RequestCompletionCallback requestCompletionCallback =
          applicationContext.getBean("clusterCoordinator", RequestCompletionCallback.class);

      final int numThreads = nifiProperties.getClusterNodeProtocolThreads();
      final Client jerseyClient =
          WebUtils.createClient(
              new DefaultClientConfig(), SslContextFactory.createSslContext(nifiProperties));
      final String connectionTimeout = nifiProperties.getClusterNodeConnectionTimeout();
      final String readTimeout = nifiProperties.getClusterNodeReadTimeout();

      replicator =
          new ThreadPoolRequestReplicator(
              numThreads,
              jerseyClient,
              clusterCoordinator,
              connectionTimeout,
              readTimeout,
              requestCompletionCallback,
              eventReporter,
              nifiProperties);
    }

    return replicator;
  }
Ejemplo n.º 13
0
  public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("ex07/beans.xml");

    // 인스턴스 생성 순서 주목하라!
    Car car1 = (Car) ctx.getBean("ex07.Car");
    System.out.println(car1);
  }
Ejemplo n.º 14
0
  @Test
  public void testResolveJmsEndpoint() throws Exception {
    reset(applicationContext);

    expect(applicationContext.getBeansOfType(EndpointComponent.class))
        .andReturn(Collections.<String, EndpointComponent>emptyMap())
        .once();
    expect(applicationContext.containsBean("connectionFactory")).andReturn(true).once();
    expect(applicationContext.getBean("connectionFactory", ConnectionFactory.class))
        .andReturn(EasyMock.createMock(ConnectionFactory.class))
        .once();

    replay(applicationContext);

    TestContext context = new TestContext();
    context.setApplicationContext(applicationContext);

    DefaultEndpointFactory factory = new DefaultEndpointFactory();
    Endpoint endpoint = factory.create("jms:Sample.Queue.Name", context);

    Assert.assertEquals(endpoint.getClass(), JmsEndpoint.class);
    Assert.assertEquals(
        ((JmsEndpoint) endpoint).getEndpointConfiguration().getDestinationName(),
        "Sample.Queue.Name");

    verify(applicationContext);
  }
 @Test
 public void testgetdeaprtmentmail() {
   ApplicationContext apc = SpringAppContext.getApplicationContext();
   DepartmentService cs = (DepartmentService) apc.getBean("DepartmentService");
   List<String> a = cs.getdepartmentLeaderidmailsbyEmpID(46);
   System.out.println(a.get(0));
 }
  public static void main(String[] args) throws InterruptedException {
    log.info("-----------Starting Redis hash testing-----------");
    ApplicationContext ctx = SpringApplication.run(HashTest.class, args);
    RedisConnectionFactory connectionFactory = ctx.getBean(RedisConnectionFactory.class);
    userTemplate = new RedisTemplate<>();
    userTemplate.setConnectionFactory(connectionFactory);
    userTemplate.setKeySerializer(userTemplate.getStringSerializer());
    userTemplate.setHashKeySerializer(userTemplate.getStringSerializer());
    userTemplate.setHashValueSerializer(new JacksonJsonRedisSerializer<UserInfo>(UserInfo.class));
    userTemplate.afterPropertiesSet();

    doubleTemplate = new RedisTemplate<>();
    doubleTemplate.setConnectionFactory(connectionFactory);
    doubleTemplate.setKeySerializer(doubleTemplate.getStringSerializer());
    doubleTemplate.setHashKeySerializer(doubleTemplate.getStringSerializer());
    doubleTemplate.setHashValueSerializer(doubleTemplate.getDefaultSerializer());
    doubleTemplate.afterPropertiesSet();

    longTemplate = new RedisTemplate<>();
    longTemplate.setConnectionFactory(connectionFactory);
    longTemplate.setKeySerializer(longTemplate.getStringSerializer());
    longTemplate.setHashKeySerializer(longTemplate.getStringSerializer());
    longTemplate.setHashValueSerializer(new LongSerializer());
    longTemplate.afterPropertiesSet();

    HashTest hashTest = ctx.getBean(HashTest.class);
    // hashTest.insert();
    // hashTest.batchInsert();
    // hashTest.insertIfAbsent();
    // hashTest.findAll();
    // hashTest.findOne();
    // hashTest.findAllKeys();
    //		hashTest.incrementDouble();
    hashTest.incrementLong();
  }
Ejemplo n.º 17
0
  public static void main(String[] args) {
    /*
     KashItHello KashItHelloBean = new KashItHello();
     KashItHelloBean.hello();
    */

    ApplicationContext context = new ClassPathXmlApplicationContext("SpringHelloWorld.xml");

    // ApplicationContext context1 = new ClassPathXmlApplicationContext("SpringHelloWorld.xml");

    KashItHello obj = (KashItHello) context.getBean("KashItHelloBean");
    // KashItHello obj1 = (KashItHello) context1.getBean("KashItHelloBean");

    obj.hello();
    // obj1.hello();

    // System.out.println("obj   : "  + obj);
    // System.out.println("obj1   : "  + obj1);

    // System.out.println("context   : "  + context);
    // System.out.println("context1   : "  + context1);

    // System.out.println("context   : "  + context.hashCode());
    // System.out.println("context1   : "  + context1.hashCode());

  }
Ejemplo n.º 18
0
  protected DataList getDataList() throws BeansException {
    if (cacheDataList == null) {
      // get datalist
      ApplicationContext ac = AppUtil.getApplicationContext();
      AppService appService = (AppService) ac.getBean("appService");
      DataListService dataListService = (DataListService) ac.getBean("dataListService");
      DatalistDefinitionDao datalistDefinitionDao =
          (DatalistDefinitionDao) ac.getBean("datalistDefinitionDao");
      String id = getPropertyString("datalistId");
      AppDefinition appDef =
          appService.getAppDefinition(
              getRequestParameterString("appId"), getRequestParameterString("appVersion"));
      DatalistDefinition datalistDefinition = datalistDefinitionDao.loadById(id, appDef);

      if (datalistDefinition != null) {
        cacheDataList = dataListService.fromJson(datalistDefinition.getJson());

        if (getPropertyString(Userview.USERVIEW_KEY_NAME) != null
            && getPropertyString(Userview.USERVIEW_KEY_NAME).trim().length() > 0) {
          cacheDataList.addBinderProperty(
              Userview.USERVIEW_KEY_NAME, getPropertyString(Userview.USERVIEW_KEY_NAME));
        }
        if (getKey() != null && getKey().trim().length() > 0) {
          cacheDataList.addBinderProperty(Userview.USERVIEW_KEY_VALUE, getKey());
        }

        cacheDataList.setActionPosition(getPropertyString("buttonPosition"));
        cacheDataList.setSelectionType(getPropertyString("selectionType"));
        cacheDataList.setCheckboxPosition(getPropertyString("checkboxPosition"));
      }
    }
    return cacheDataList;
  }
Ejemplo n.º 19
0
  @Scope("session")
  @RequestMapping(value = "/unjoin_company", method = RequestMethod.GET)
  public String unjoinCustomer(Locale locale, Model model, HttpServletRequest request) {

    try {

      ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
      CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

      int ID = Integer.parseInt(request.getParameter("id"));
      /*String name = request.getParameter("name").toString();
      int age = Integer.parseInt(request.getParameter("age"));

      Customer user = new Customer(ID, name, age);*/

      String sql = "UPDATE customer SET Assigned = \"\" WHERE CUST_ID = " + ID;
      customerDAO.unjoinCustomer(sql);

      ID = Integer.parseInt(request.getParameter("companyID"));
      sql = "UPDATE companies SET Count = Count + 1 WHERE ID = " + ID;
      customerDAO.unjoinCustomer(sql);

    } catch (Throwable q) {

    }
    return "redirect:/companies";
  }
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("konfiguracja.xml");
    UsersRepository usersRepository =
        context.getBean("repozytoriumUzytkownikow", UsersRepository.class);

    User konrad = usersRepository.createUser("Konrad");
  }
Ejemplo n.º 21
0
  @Scope("session")
  @RequestMapping(value = "/search_list", method = RequestMethod.GET)
  public ModelAndView searchList(HttpServletRequest request) {

    ModelAndView model = new ModelAndView("searchList");
    try {

      String industry = request.getParameter("industry").toString();

      ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
      CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

      Map<Integer, HashMap<String, String>> ResultMap =
          new HashMap<Integer, HashMap<String, String>>();
      ResultMap =
          customerDAO.SQLquery(
              "SELECT companies.*,  NameIndustry FROM companies LEFT JOIN industry"
                  + " ON companies.Industry = industry.ID WHERE companies.Industry = "
                  + industry);

      model.addObject("ResultMap", ResultMap);

    } catch (Throwable q) {

      return model;
    }
    return model;
  }
Ejemplo n.º 22
0
  /**
   * Adjust the command to suit the environment.
   *
   * @param command The command to run.
   * @return The adjusted command.
   */
  public List<String> prepareCommand(List<String> command) {
    ApplicationContext appContext = ApplicationContextProvider.getApplicationContext();
    NdgConfigManager ndgConfigManager = (NdgConfigManager) appContext.getBean("ndgConfigManager");

    String loc = ndgConfigManager.getConfig().getGdalLocation();
    if (loc == null) throw new IllegalStateException("GDAL location is not configured.");

    Path gdalBinDir = Paths.get(loc, "bin");
    Path gdalCmdPath = gdalBinDir.resolve(command.get(0));

    // Patch in path to GDAL, if appropriate.
    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add(gdalCmdPath.toString());

    log.trace("cma [0] = {}", command.get(0));

    // Remove windows-style backslashes.
    for (int i = 1; i < command.size(); ++i) {
      log.trace("cma [{}] = {}", i, command.get(i));
      String s = command.get(i).replace('\\', '/');
      cmd.add(s);
    }

    String commandStr = StringUtils.join(cmd, " ");
    log.debug("Attempting to run: " + commandStr);

    return cmd;
  }
Ejemplo n.º 23
0
  @RequestMapping("/edit_customer")
  public ModelAndView edit_customer(HttpServletRequest request) {
    int ID = Integer.parseInt(request.getParameter("userID"));

    ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");

    Map<String, String> user = new HashMap<String, String>();

    CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");

    user = customerDAO.findCurrentCustomerById(ID);

    IndustryDAO industryDAO = (IndustryDAO) context.getBean("industryDAO");
    List<Industry> industries = new ArrayList<Industry>();
    industries = industryDAO.getIndustriesList();

    ModelAndView model = new ModelAndView("edit_customer");
    model.addObject("userData", user);
    model.addObject("industryList", industries);
    /**
     * <c:forEach items="${countries}" var="country"> <option
     * value="${country.key}">${country.value}</option> </c:forEach>
     */
    return model;
  }
Ejemplo n.º 24
0
 private void init() {
   // message
   data = (Map<String, Object>) UI.getCurrent().getData();
   locale = (Locale) data.get("locale");
   timeZone = (TimeZone) data.get("timeZone");
   termResource = new TermResource(locale);
   messageResource = new MessageResource(locale);
   // service
   context = ((Workbench) UI.getCurrent()).getApplicationContext();
   candStageInterviewerService =
       (CandStageInterviewerService) context.getBean("candStageInterviewerService");
   codeDataService = (CodeDataService) context.getBean("codeDataService");
   schoolService = (SchoolService) context.getBean("schoolService");
   majorService = (MajorService) context.getBean("majorService");
   candProfileReadService = (CandProfileReadService) context.getBean("candProfileReadService");
   candFavoriteService = (CandFavoriteService) context.getBean("candFavoriteService");
   // param
   currentUser = (Account) data.get("account");
   // temp
   candidateService = (CandidateService) context.getBean("candidateService");
   requisitionService = (RequisitionService) context.getBean("requisitionService");
   accountService = (AccountService) context.getBean("accountService");
   candApplyRequisitionService =
       (CandApplyRequisitionService) context.getBean("candApplyRequisitionService");
 }
Ejemplo n.º 25
0
 public static void main(String[] args) {
   ApplicationContext context =
       new ClassPathXmlApplicationContext(
           "org/kasource/kaevent/example/spring/annotations/channel/channel-context.xml");
   Thermometer thermometer = (Thermometer) context.getBean("thermometer");
   thermometer.run();
 }
Ejemplo n.º 26
0
  private void initApiInfo() throws Exception {
    int apiCounter = 0;
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(Controller.class);

    if (beanNames == null) {
      logger.info("No controller bean found. stop server and fix it.");
      throw new Exception("No controller bean found. stop server and fix it.");
    }

    Map<String, Object> checkMap = new HashMap<String, Object>();
    for (String beanName : beanNames) {
      logger.info("Controller bean found: " + beanName);
      Class<?> beanType = applicationContext.getType(beanName);

      Method[] methods = beanType.getMethods();
      for (Method method : methods) {
        if (method.getAnnotation(Api.class) != null
            && method.getAnnotation(RequestMapping.class) != null) {
          logger.info("Controller Api Method found: " + method.getName());
          if (checkMap.get(method.getName()) != null) {
            logger.info("Controller method name is duplicated! stop server and fix it.");
            throw new Exception("Controller method name is duplicated! stop server and fix it.");
          }
          checkMap.put(method.getName(), new Object());
          apiCounter++;
        }
      }
    }
    logger.info("Total {} api listed.", apiCounter);
    this.apiInfoCache = new ConcurrentHashMap<String, ApiInfo>();
  }
Ejemplo n.º 27
0
  public static void main(String[] args) {
    ApplicationContext context =
        new ClassPathXmlApplicationContext("step08/application-context02.xml");

    // @Autowired 처리후!
    System.out.println(context.getBean("c1"));
  }
Ejemplo n.º 28
0
  public static void main(String[] args) {

    // 1 - Instanciation du context Spring en faisant référence au fichier des beans 'beans.xml'
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    // 2- Recuperation d'un bean du conteneur
    IBankonetMetier bankometier1 = (IBankonetMetier) context.getBean("bankonetMetier");

    System.out.println("*****************TEST FONCTIONS DAO*******************");

    // 3-Utilisation du bean
    try {
      bankometier1.ajoutClient(
          new Client(
              "monkey D",
              "luffy",
              "gumgum",
              "bazooka",
              new Adresse(26, "mangrove 41", "CelestIsland")));
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    // bankometier1.effacerClient(1);
    // System.out.println("\nListe des clients de bankometier1"+bankometier1.listerClient());
    // System.out.println(bankometier1.findClients("fajoux"));
    // bankometier1.effacerClient(1551);

  }
Ejemplo n.º 29
0
  @Override
  public String execute() throws Exception {

    ActionContext ctx = ActionContext.getContext();

    ServletContext sc = (ServletContext) ctx.get(ServletActionContext.SERVLET_CONTEXT);

    ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    CourseManagerImpl cmi = (CourseManagerImpl) appContext.getBean("CourseManagerImpl");
    StudentManagerImpl smi = (StudentManagerImpl) appContext.getBean("StuManagerImpl");

    List cmiList = cmi.getCourses();
    List smiList = smi.getStudents();

    Map cmiMap = new HashMap();
    Map smiMap = new HashMap();

    for (int i = 0; i < cmiList.size(); i++) {
      Course course = (Course) cmiList.get(i);
      cmiMap.put(course.getCoursId(), course.getCoursName());
    }

    for (int i = 0; i < smiList.size(); i++) {
      Student student = (Student) smiList.get(i);
      smiMap.put(student.getStuId(), student.getStuName());
    }

    ActionContext actionContext = ActionContext.getContext();
    Map session = actionContext.getSession();
    session.put("cmiMap", cmiMap);
    session.put("smiMap", smiMap);
    return SUCCESS;
  }
Ejemplo n.º 30
0
 @Test
 public void testFlightRepo() {
   ApplicationContext container = new ClassPathXmlApplicationContext("ex1/ex1-config.xml");
   FlightRepository flightRepo = container.getBean("flightRepo", FlightRepository.class);
   Assert.assertNotNull(flightRepo);
   Assert.assertTrue(flightRepo.getAvailableFlights().size() > 0);
 }