Adding TreeView to a TableCeell in javafx - treeview

I need to add a TreeView to each cell in a particular column of a table.I am able to add Strings but I am not able to add TreeView. How can I do this?
This is my NodeInfo class
public class NodeInfo{
private TreeView<String> nodeTree;
private TreeItem<String> root;
private final Image rootIcon=new Image(getClass().getResourceAsStream("/images/nodes.gif"));
private final Image folderIcon=new Image(getClass().getResourceAsStream("/images/folder.gif"));
public void settreeView(String s)
{
nodeTree = new TreeView<>();
nodeTree.setEditable(true);
root = new TreeItem<>("Rootnode", new ImageView(rootIcon));
root.setExpanded(false);
nodeTree.setRoot(root);
for(int i=0;i<3; i++)
{
root.getChildren().add(new TreeItem<>(sharedFolders.get(i), new ImageView(folderIcon)));
}
}
public TreeView<String> gettreeView()
{
return nodeTree;
}
}
And this is controller class for UI
public class GrapevineController implements Initializable {
#FXML
private TableView<NodeInfo> tableView;
#FXML
private TableColumn<NodeInfo, TreeView<String>> nodeTree;
#FXML
private TableColumn<NodeInfo, String> name;
#FXML
private TableColumn<NodeInfo, String> favourite;
#FXML
private TableColumn<NodeInfo, String> updates;
#FXML
public static ObservableList<NodeInfo> sourceTree = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle r){
tableView.setEditable(true);
nodeTree.setCellValueFactory(new PropertyValueFactory<NodeInfo, TreeView<String>> ("treeView"));
name.setCellValueFactory(new PropertyValueFactory<NodeInfo, String>("MacAddress"));
favourite.setCellValueFactory(new PropertyValueFactory<NodeInfo, String>("favourites"));
updates.setCellValueFactory(new PropertyValueFactory<NodeInfo, String>("update"));
tableView.setItems(sourceTree);
}

Related

Entity listener can inject other Spring dependencies but not repository

I have this entity listener class:
#Component
public class AssignmentListener {
private KafkaService kafkaService;
private String topic;
private AssignmentMapper assignmentMapper;
private AttachmentRepository attachmentRepository;
#Autowired
public final void setKafkaService(KafkaService kafkaService) {
this.kafkaService = kafkaService;
}
#Autowired
public final void setTopic(
#Value("${topic}") String topic
) {
this.topic = topic;
}
#Autowired
public final void setAssignmentMapper(AssignmentMapper assignmentMapper) {
this.assignmentMapper = assignmentMapper;
}
#Autowired
public final void setAttachmentRepository(AttachmentRepository attachmentRepository) {
this.attachmentRepository = attachmentRepository;
}
#PostPersist
#PostUpdate
#Transactional("transactionManager")
#TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
public void postUpdate(Assignment assignment) {
var attachments = attachmentRepository.findAllByAssignmentId(assignment.getId());
var dto = assignmentMapper.mapToKafkaMessage(assignment);
dto.setAttachments(
attachments.stream()
.map(Attachment::getPath)
.collect(Collectors.toSet())
);
kafkaService.sendMessage(
topic,
dto
);
}
}
and it worked normally until adding this last field which is repository. All other dependencies were injected however no matter what I do this won't get injected. Just to mention this is happening in tests. Do you have any suggestion?

How to test GET request with body in Spring RestController?

I have a rest controller like this;
#RestController
#RequiredArgsConstructor
#RequestMapping(PO)
public class PoController {
private final PoService service;
#GetMapping(value = FILTER, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<List<PoDTO>> filter(PoFilterCriteria poFilterCriteria) {
return ok().body(service.getPos(poFilterCriteria));
}
}
And I want to write an unit test for it but I couldn't achieve to mock the service to return list.
This is my poFilterCriteria model;
#Data
public class PoFilterCriteria {
private double hp;
private FilterOperationType hpOperationType;
private double attack;
private FilterOperationType attackOperationType;
private double defense;
private FilterOperationType defenseOperationType;
}
And this is my test;
#WebMvcTest(value = PoController.class)
class PoControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private PoService service;
private PoDTO poDTO;
private List<PoDTO> poDTOList;
#BeforeEach
void setUp() {
poDTOList = new ArrayList<>();
poDTO = new Po();
poDTOList.add(poDTO);
}
#Test
public void filter_success() throws Exception {
PoFilterCriteria poFilterCriteria= new PoFilterCriteria ();
poFilterCriteria.setAttack(40);
poFilterCriteria.setAttackOperationType(GT);
poFilterCriteria.setHp(49);
poFilterCriteria.setHpOperationType(EQ);
poFilterCriteria.setDefense(60);
poFilterCriteria.setDefenseOperationType(LT);
when(service.getPos(poFilterCriteria)).thenReturn(poDTOList);
mockMvc.perform(get(PO + FILTER)
.param("hp", String.valueOf(40))
.param("hpOperationType", String.valueOf(GT))
.param("attack", String.valueOf(49))
.param("attackOperationType", String.valueOf(EQ))
.param("defense", String.valueOf(60))
.param("defenseOperationType", String.valueOf(LT))
.contentType(APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().json(new ObjectMapper().writeValueAsString(poDTOList)));
}
}
But the list that should return with size of 1 is returning empty.
What did I do wrong?
org.mockito.ArgumentMatchers#any(java.lang.Class)
when(service.getPos(any(PoFilterCriteria.class))).thenReturn(poDTOList);
or
org.mockito.ArgumentMatchers#same
when(service.getPos(same(poFilterCriteria))).thenReturn(poDTOList);

How to set a tableview in JavaFX in initialize method

Hi I'm new to JavaFX and want to populate a tableview with data
I use not the programmatic way I create the tableview with scene builder and have a controller file . I have a data file for the getters and setters already and created a observable list
public class Controller implements Initializable {
#FXML TableView<Bew> tableV;
#FXML TableColumn<Bew, String> nameCol =new TableColumn<>("Name");
#FXML TableColumn<Bew, String> dateCol =new TableColumn<>("Datum");
#FXML TableColumn<Bew, String> actionCol =new TableColumn<>("Aktivität");
#FXML TableColumn<Bew, String> infoCol =new TableColumn<>("Info");
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
SQLiteDB DB = new SQLiteDB();
ObservableList<Bew> list = DB.getData();
tableV.setItems(list);
}
public ObservableList<Bew> getData() {
ObservableList<Bew> bewList = FXCollections.observableArrayList();
bewList.add(new Bew("Rita", "01.12.1920", "Gespräch", "gud"));
bewList.add(new Bew("Marc", "14.03.1930", "Spaziergang", "gud"));
bewList.add(new Bew("Peter", "27.01.1901", "dfdsfdsfdsfdsf", "gud"));
bewList.add(new Bew("John", "12.12.1912", "dfdsfdsfdsfdsf", "gud"));
return bewList;
}
When I run the code no error appears but no data in tableview
Any help?

How to bind BeanItemContainer to Combobox

I have BeanItemContainer, which i load from database via jdbc:
BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, mybeanDao.findAll());
and this is how i attach it to combobox:
Combobox combo = new Combobox();
combobox.setContainerDataSource(myBeans);
So far, so good. I received what i want, but for now i have a problem -
How do i get actual id that has been selected? This must be synchronized (id selected in combobox is actual entry in database).
I have no idea, how to solve this problem
Please help
P.S MyBean class
public class MyBean {
private Long id;
private String field1;
*** getters /setters ***
and toString() {} method
}
Here is the code:
#Theme("mytheme")
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
layout.setSpacing(true);
setContent(layout);
BeanItemContainer myBeans = new BeanItemContainer<>(MyBean.class, getBeans());
ComboBox combo = new ComboBox();
combo.setContainerDataSource(myBeans);
combo.setItemCaptionMode(AbstractSelect.ItemCaptionMode.PROPERTY);
combo.setItemCaptionPropertyId("field");
combo.addValueChangeListener(new Property.ValueChangeListener() {
#Override
public void valueChange(Property.ValueChangeEvent event) {
MyBean bean = (MyBean) combo.getValue();
Notification notif = new Notification("Selected Bean Id: "+bean.getId(), Notification.Type.TRAY_NOTIFICATION);
notif.setPosition(Position.TOP_CENTER);
notif.show(Page.getCurrent());
}
});
layout.addComponent(combo);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
public class MyBean {
private Long id;
private String field;
public MyBean(Long id, String field) {
this.id = id;
this.field = field;
}
public Long getId() {
return id;
}
public String getField() {
return field;
}
}
public ArrayList<MyBean> getBeans() {
ArrayList<MyBean> beans = new ArrayList<>();
MyBean bean = new MyBean(1l, "Vikrant");
beans.add(bean);
bean = new MyBean(2l, "Rampal");
beans.add(bean);
bean = new MyBean(3l, "viky");
beans.add(bean);
return beans;
}
}
If I understood the question correctly combo.getValue() should give you the MyBean instance relative to the current selection (or null if no item is selected)

Generate static map from database using a singleton class also using spring configuration #Autowired

I need to create an unmodifiable map generated from data obtained by querying a database. How, or can I, or is there a better way to do this using spring annotations?
I ran into a problem when creating a singleton for my Regions class and then trying to #Autowire in a RegionService to grab the object from the DAO. The problem is that spring can't instantiate the RegionService because it needs to instantiate the static singleton class Regions which needs to get data from the database as shown below in the constructor.
Please see me classes below (I've removed multiple unneeded methods that don't pertain to this question):
public final class Region {
private static final String DEFAULT_SEPERATOR = "-";
private final Integer key;
private final String description;
public Region(Integer pKey, String pDescription) {
this.key = pKey;
this.description = pDescription;
}
public Integer getKey() {
return this.key;
}
public String getValue() {
return this.description;
}
}
Here is my singleton:
public final class Regions {
private static Regions regionsInstance = null;
#Autowired
private RegionService regionService;
static Map<Integer, Region> regions;
private Regions() {
final Map<Integer, Region> tempRegions = new HashMap<Integer, Region>();
for (final Region region : this.regionService.retrieveAll()) {
tempRegions.put(region.getKey(), region);
}
regions = Collections.unmodifiableMap(tempRegions);
}
public static synchronized Regions getRegionsInstance() {
if (regionsInstance == null) {
regionsInstance = new Regions();
}
return regionsInstance;
}
public Region getRegion(final Integer pKey) {
return regions.get(pKey);
}
public List<Region> getRegions() {
return (List<Region>) regions.values();
}
}
My DAO and Service are just interfaces, no need to post those, here are my Impls:
#Service
public class RegionServiceImpl implements RegionService {
#Autowired
private RegionDAO regionDao;
#Override
public List<Region> retrieveAll() {
return this.regionDao.retrieveAll();
}
}
My DAOImpl (tested and works, just posting to give you the full picture):
#Repository
public class RegionDAOImpl implements RegionDAO {
private static final String SQL_RETRIEVE_REGIONS = "some random SQL";
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public List<Region> retrieveAll() {
try {
return this.jdbcTemplate.query(SQL_RETRIEVE_REGIONS, new ResultSetExtractor<List<Region>>() {
#Override
public List<Region> extractData(ResultSet rs) throws SQLException, DataAccessException {
return RegionDAOImpl.this.mapRegionData(rs);
}
});
} catch (final DataAccessException dae) {
throw new DaoException("Could not retrieve regionList from database. " + dae);
}
}
protected final List<Region> mapRegionData(ResultSet rs) throws SQLException {
final List<Region> regionList = new ArrayList<Region>();
while (rs.next()) {
regionList.add(new Region(rs.getInt("REGION_CD"), rs.getString("REGION_TXT")));
}
return Collections.unmodifiableList(regionList);
}
}
Then I run my test(I took out unneeded crap):
#..annotated with things you don't need to know
public class RetrieveRegionsTest {
#Autowired
private Regions r;
#Test
public void getAndLogRegion() {
final List<Region> regionDescriptions = new ArrayList<Region>(this.r.getRegions());
for (final Region region : regionDescriptions) {
LOGGER.info(region.getValue());
}
}
Yes my configuration and classpaths are set up properly. I can get this to work other ways, just not by accessing the Regions singleton which is what I want. Now I know I could take off the #Autowired on the RegionService in my Regions singleton and just create a new instance of RegionService, but that would defeat the purpose of springs #Autowired feature.
Any thoughts, ideas, comments?

Resources