View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstarts.cdi.service;
18  
19  import java.util.List;
20  
21  import javax.enterprise.context.RequestScoped;
22  import javax.faces.application.FacesMessage;
23  import javax.faces.context.FacesContext;
24  import javax.inject.Inject;
25  import javax.inject.Named;
26  
27  /**
28   * JSF backing bean that demonstrates CDI injection.
29   * 
30   * Bean name overridden to "itemBean" to be accessible from view with this name.
31   * 
32   * @author Ievgen Shulga
33   */
34  @Named("itemBean")
35  @RequestScoped
36  public class ItemBean {
37      @Inject
38      private ItemService itemService;
39      @Inject
40      private FacesContext context;
41      private List<Item> items;
42      private List<String> itemHistory;
43      private String name;
44      private static final String EMPTY_STRING = "";
45  
46      public void add() {
47          if (name == EMPTY_STRING) {
48              FacesMessage fm = new FacesMessage("Name can't be empty");
49              context.addMessage(fm.getSummary(), fm);
50              refresh();
51              return;
52          }
53          Item item = new Item();
54          item.setName(name);
55          itemService.create(item);
56          name = EMPTY_STRING;
57          refresh();
58      }
59  
60      private void refresh() {
61          itemHistory = History.getItemHistory();
62          items = itemService.getList();
63      }
64  
65      public List<Item> getItems() {
66          return items;
67      }
68  
69      public void setItems(List<Item> items) {
70          this.items = items;
71      }
72  
73      public String getName() {
74          return name;
75      }
76  
77      public void setName(String name) {
78          this.name = name;
79      }
80  
81      public List<String> getItemHistory() {
82          return itemHistory;
83      }
84  
85      public void setItemHistory(List<String> itemHistory) {
86          this.itemHistory = itemHistory;
87      }
88  
89  }