kaitai struct code unable to get output in eclipse ide - eclipse

hi i am very newer to kaitai struct, how do i run a code in eclipse which
is parsed to java(target langage) on kaitai struct webide, i have gone
through the kaitai struct docs, still i have some doubts, can someone help
me? i have posted parsed java class and main class also
package com.ccx.ccxgw.message.parsers;
import io.kaitai.struct.ByteBufferKaitaiStream;
import io.kaitai.struct.KaitaiStruct;
import io.kaitai.struct.KaitaiStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.nio.charset.Charset;
public class LocationRecord extends KaitaiStruct {
public Map<String, Integer> _attrStart = new HashMap<String, Integer>();
public Map<String, Integer> _attrEnd = new HashMap<String, Integer>();
public Map<String, ArrayList<Integer>> _arrStart = new HashMap<String,
ArrayList<Integer>>();
public Map<String, ArrayList<Integer>> _arrEnd = new HashMap<String,
ArrayList<Integer>>();
public static LocationRecord fromFile(String fileName) throws IOException {
return new LocationRecord(new ByteBufferKaitaiStream(fileName));
}
public static String[] _seqFields = new String[] { "imei", "reserved1",
"reserved2", "latrawintpart", "latrawfloatpart", "lonrawintpart",
"lonrawfloatpart", "reserved3", "lbsinfo", "ta", "p", "mt", "fff", "ddd" };
public LocationRecord(KaitaiStream _io) {
this(_io, null, null);
}
public LocationRecord(KaitaiStream _io, KaitaiStruct _parent) {
this(_io, _parent, null);
}
public LocationRecord(KaitaiStream _io, KaitaiStruct _parent, LocationRecord
_root) {
super(_io);
this._parent = _parent;
this._root = _root == null ? this : _root;
}
public void _read() {
_attrStart.put("imei", this._io.pos());
this.imei = this._io.readBytes(15);
_attrEnd.put("imei", this._io.pos());
_attrStart.put("reserved1", this._io.pos());
this.reserved1 = this._io.readBytes(6);
_attrEnd.put("reserved1", this._io.pos());
_attrStart.put("reserved2", this._io.pos());
this.reserved2 = this._io.readBytes(6);
_attrEnd.put("reserved2", this._io.pos());
_attrStart.put("latrawintpart", this._io.pos());
this.latrawintpart = this._io.readU2be();
_attrEnd.put("latrawintpart", this._io.pos());
_attrStart.put("latrawfloatpart", this._io.pos());
this.latrawfloatpart = this._io.readU2be();
_attrEnd.put("latrawfloatpart", this._io.pos());
_attrStart.put("lonrawintpart", this._io.pos());
this.lonrawintpart = this._io.readU2be();
_attrEnd.put("lonrawintpart", this._io.pos());
_attrStart.put("lonrawfloatpart", this._io.pos());
this.lonrawfloatpart = this._io.readU2be();
_attrEnd.put("lonrawfloatpart", this._io.pos());
_attrStart.put("reserved3", this._io.pos());
this.reserved3 = this._io.readBytes(3);
_attrEnd.put("reserved3", this._io.pos());
_attrStart.put("lbsinfo", this._io.pos());
this.lbsinfo = new String(this._io.readBytes(3),
Charset.forName("ASCII"));
_attrEnd.put("lbsinfo", this._io.pos());
_attrStart.put("ta", this._io.pos());
this.ta = new String(this._io.readBytes(8), Charset.forName("ASCII"));
_attrEnd.put("ta", this._io.pos());
_attrStart.put("p", this._io.pos());
this.p = new String(this._io.readBytes(8), Charset.forName("ASCII"));
_attrEnd.put("p", this._io.pos());
_attrStart.put("mt", this._io.pos());
this.mt = new String(this._io.readBytes(8), Charset.forName("ASCII"));
_attrEnd.put("mt", this._io.pos());
_attrStart.put("fff", this._io.pos());
this.fff = new String(this._io.readBytes(8), Charset.forName("ASCII"));
_attrEnd.put("fff", this._io.pos());
_attrStart.put("ddd", this._io.pos());
this.ddd = new String(this._io.readBytes(8), Charset.forName("ASCII"));
_attrEnd.put("ddd", this._io.pos());
}
private Double latitude;
public Double latitude() {
if (this.latitude != null)
return this.latitude;
double _tmp = (double) ((latitudeintpart() + latitudefloatpart()));
this.latitude = _tmp;
return this.latitude;
}
private Double longitude;
public Double longitude() {
if (this.longitude != null)
return this.longitude;
double _tmp = (double) ((longitudeintpart() + longitudefloatpart()));
this.longitude = _tmp;
return this.longitude;
}
private Double latitudefloatpart;
public Double latitudefloatpart() {
if (this.latitudefloatpart != null)
return this.latitudefloatpart;
double _tmp = (double) ((((((latrawintpart() * 10000) +
latrawfloatpart()) - (latitudeintpart() * 1000000)) * 0.0001) / 60));
this.latitudefloatpart = _tmp;
return this.latitudefloatpart;
}
private Double longitudefloatpart;
public Double longitudefloatpart() {
if (this.longitudefloatpart != null)
return this.longitudefloatpart;
double _tmp = (double) ((((((lonrawintpart() * 10000) +
lonrawfloatpart()) - (longitudeintpart() * 1000000)) * 0.0001) / 60));
this.longitudefloatpart = _tmp;
return this.longitudefloatpart;
}
private Integer longitudeintpart;
public Integer longitudeintpart() {
if (this.longitudeintpart != null)
return this.longitudeintpart;
int _tmp = (int) ((((lonrawintpart() * 10000) + lonrawfloatpart()) /
1000000));
this.longitudeintpart = _tmp;
return this.longitudeintpart;
}
private Integer latitudeintpart;
public Integer latitudeintpart() {
if (this.latitudeintpart != null)
return this.latitudeintpart;
int _tmp = (int) ((((latrawintpart() * 10000) + latrawfloatpart()) /
1000000));
this.latitudeintpart = _tmp;
return this.latitudeintpart;
}
private byte[] imei;
private byte[] reserved1;
private byte[] reserved2;
private int latrawintpart;
private int latrawfloatpart;
private int lonrawintpart;
private int lonrawfloatpart;
private byte[] reserved3;
private String lbsinfo;
private String ta;
private String p;
private String mt;
private String fff;
private String ddd;
private LocationRecord _root;
private KaitaiStruct _parent;
public byte[] imei() { return imei; }
public byte[] reserved1() { return reserved1; }
public byte[] reserved2() { return reserved2; }
public int latrawintpart() { return latrawintpart; }
public int latrawfloatpart() { return latrawfloatpart; }
public int lonrawintpart() { return lonrawintpart; }
public int lonrawfloatpart() { return lonrawfloatpart; }
public byte[] reserved3() { return reserved3; }
public String lbsinfo() { return lbsinfo; }
public String ta() { return ta; }
public String p() { return p; }
public String mt() { return mt; }
public String fff() { return fff; }
public String ddd() { return ddd; }
public LocationRecord _root() { return _root; }
public KaitaiStruct _parent() { return _parent; }
}
main class is below
package com.ccx.ccxgw.message.parsers;
public class test {
public static void main(String[] args) {
try {
LocationRecord lr =
LocationRecord.fromFile("D:\\Projects\\CcxParser\\CcxParsers\\loc.data");
lr.imei();
lr.reserved1();
lr.reserved2();
lr.latrawintpart();
lr.latrawfloatpart();
lr.lonrawintpart();
lr.lonrawfloatpart();
lr.reserved3();
lr.lbsinfo();
lr.ta();
lr.p();
lr.mt();
lr.fff();
lr.ddd();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
kindly suggest me what modification should be done,, if possible provide me
snippet for main class to call kaitai struct class methods. and i want to parse this message {354105059135656,010104,164536,12.888888,77.5564499,100,lbs,ta,p,mt,fff,ddd}

Related

Specify which java type to decode an embedded document to

I have a simple java type
public class Type1_ {
private int number1;
private int number2;
public Type1_(int number1, int number2) {
this.number1 = number1;
this.number2 = number2;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
#Override
public String toString() {
return "Type1_{number1=" + number1 + ", number2=" + number2 + '}';
}
public static Type1_ random() {
return new Type1_(new SecureRandom().nextInt(), new SecureRandom().nextInt());
}
}
Created a simple Codec<Type1_> for this type (with loggers to know when or if they are being used)
public class Type1_Codec implements Codec<Type1_> {
#Override
public Type1_ decode(BsonReader reader, DecoderContext decoderContext) {
reader.readStartDocument();
final int number1 = reader.readInt32("number1");
final int number2 = reader.readInt32("number2");
reader.readEndDocument();
final Type1_ type1_ = new Type1_(number1, number2);
APP_LOGGER.debug(type1_);
return type1_;
}
#Override
public void encode(BsonWriter writer, Type1_ value, EncoderContext encoderContext) {
writer.writeStartDocument();
writer.writeInt32("number1", value.getNumber1());
writer.writeInt32("number2", value.getNumber2());
writer.writeEndDocument();
APP_LOGGER.debug(value);
}
#Override
public Class<Type1_> getEncoderClass() {
return Type1_.class;
}
}
Added the codec to a registry to be used in MongoClient
public class CustomCodecRegistriesFactory {
public static CodecRegistry getDefault() {
return MongoClientSettings.getDefaultCodecRegistry();
}
public static CodecRegistry getDefaultWithType1_() {
return CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(new Type1_Codec()), getDefault());
}
}
public class MongoDBClientConfig {
public static MongoClient buildMongoClientWithCustomCodec(final CodecRegistry codecRegistry) {
return MongoClients.create(MongoClientSettings.builder()
.applyToClusterSettings(builder -> {
builder.hosts(Arrays.asList(new ServerAddress(url(), port())));
})
.codecRegistry(codecRegistry)
.build());
}
}
Created a test that uses a codec registry where the Type1_Codec is included and attempt to insert (encode) and read (decode) Type1_
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class Codecs {
#Test
public void demonstrate_simpleCustomCodec() {
final MongoClient mongoClient = buildMongoClientWithCustomCodec(CustomCodecRegistriesFactory.getDefaultWithType1_());
final MongoDatabase db = mongoClient.getDatabase("db_" + new SecureRandom().nextInt(Integer.MAX_VALUE));
final String collectionName = "col1";
db.createCollection(collectionName);
final MongoCollection<Document> col1 = db.getCollection(collectionName);
int idCounter = 0;
final String type1_field = "type1_";
printTitle("Inserting Documents");
for (int i = 0; i < 10; i++) {
/*Encoding is done at insertion*/
col1.insertOne(new Document(ID, idCounter++).append(type1_field, Type1_.random()));
}
printDocumentMongoCollection(col1);
printMongoCollectionJackson(col1);
printTitle("Attempting Decoding");
/*attempt decoding*/
// final Type1_ type1_value = col1.find().first().get(type1_field, Type1_.class);
// System.out.println(type1_value);
}
}
The problem is in the decoding part.
How do i specify for MongoClient that i want a specific document to be decoded into Type1_ type?
The commented out code will attempt to cast a Document to Type1_ and will fail.
use db.getCollection(collectionName, Type1_.class) to "type" your collection. That should pull your codec in to play automatically for you.

JavaFX 8 TableView not populating from ObservableList (no FXML)

I believe I've searched all of the similar questions, but still am not seeing my issue anywhere. I am populating an ObservableList from a database which is succeeding per my Console output. I have a multiple controller setup for a school project to create a scheduler app. I have a root controller which functions as the borderPane, two functional controllers for Appointments and Customers which are all Singleton, and a shared DataView controller which is not to allow each view to instantiate its' own DataView. I've implemented toString on each of the controllers to spit out what the values and/or object Ids of each element are and everything seems to line up. I can't for the life of me figure out why the ListView or TableView aren't outputting the bound data. Here's the view data that I'm trying to bind to both ListView and TableView
public class AppointmentView implements IAppointmentView {
private final ZonedDateTime createdDate;
private final String createdBy;
// Interface needs these components
private ReadOnlyStringProperty title;
private ReadOnlyStringProperty description;
private ReadOnlyStringProperty location;
private ReadOnlyStringProperty contact;
private ReadOnlyStringProperty url;
private ReadOnlyStringProperty customerName;
private ReadOnlyObjectProperty<ZonedDateTime> start;
private ReadOnlyObjectProperty<ZonedDateTime> end;
private ReadOnlyProperty<ZonedDateTime> lastUpdated;
/***
*
* #param title
* #param description
* #param location
* #param contact
* #param url
* #param customerName
* #param start
* #param end
* #param createDate
* #param createdBy
* #param lastUpdate
*/
public AppointmentView(String title, String description, String location, String contact, String url, String customerName, Timestamp start, Timestamp end, Timestamp createDate, String createdBy, Timestamp lastUpdate) {
this.title = new SimpleStringProperty(title);
this.description = new SimpleStringProperty(description);
this.location = new SimpleStringProperty(location);
this.contact = new SimpleStringProperty(contact);
this.customerName = new SimpleStringProperty(customerName);
this.start = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(start.toInstant(), ZoneId.systemDefault()));
this.end = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(end.toInstant(), ZoneId.systemDefault()));
this.lastUpdated = new SimpleObjectProperty<>(ZonedDateTime.ofInstant(lastUpdate.toInstant(), ZoneId.systemDefault()));
this.url = new SimpleStringProperty(url);
this.createdDate = ZonedDateTime.ofInstant(createDate.toInstant(), ZoneId.systemDefault());
this.createdBy = createdBy;
}
public String getTitle() {
return title.getValue();
}
ReadOnlyStringProperty titleProperty() {
return title;
}
public String getDescription() {
return description.getValue();
}
ReadOnlyStringProperty descriptionProperty() {
return description;
}
public String getLocation() {
return location.getValue();
}
ReadOnlyStringProperty locationProperty() {
return location;
}
public String getContact() {
return contact.getValue();
}
ReadOnlyStringProperty contactProperty() {
return contact;
}
public String getUrl() {
return url.getValueSafe();
}
ReadOnlyStringProperty urlProperty() {
return url;
}
public String getCustomerName() {
return customerName.getValue();
}
ReadOnlyStringProperty customerNameProperty() {
return customerName;
}
public ZonedDateTime getStart() {
return ZonedDateTime.ofInstant(start.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> startProperty() {
return start;
}
public ZonedDateTime getEnd() {
return ZonedDateTime.ofInstant(end.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> endProperty() {
return end;
}
public LocalDate getCreateDate() {
return createdDate.toLocalDate();
}
public String getCreatedBy() {
return createdBy;
}
public ZonedDateTime getLastUpdate() {
return ZonedDateTime.ofInstant(lastUpdated.getValue().toInstant(), ZoneId.systemDefault());
}
ReadOnlyProperty<ZonedDateTime> lastUpdatedProperty() {
return lastUpdated;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("AppointmentView{");
sb.append("createdDate=").append(createdDate);
sb.append(", createdBy='").append(createdBy).append('\'');
sb.append(", titleProperty=").append(title);
sb.append(", descriptionProperty=").append(description);
sb.append(", locationProperty=").append(location);
sb.append(", contactProperty=").append(contact);
sb.append(", urlProperty=").append(url);
sb.append(", customerName=").append(customerName);
sb.append(", startProperty=").append(start);
sb.append(", endProperty=").append(end);
sb.append(", lastUpdated=").append(lastUpdated);
sb.append('}');
return sb.toString();
}
}
Here's the AppViewController:
public class AppViewController extends BorderPane {
private BorderPane rootPane;
private MenuBar menuBar;
private Menu fileMenu;
private Menu editMenu;
private Menu reportMenu;
private Menu helpMenu;
private MenuItem closeMenuItem;
private MenuItem copyMenuItem;
private MenuItem monthlyAppointmentReportMenuItem;
private MenuItem consultantScheduleMenuItem;
private MenuItem customersByCountryMenuItem;
private MenuItem aboutMenuItem;
private VBox vbAppView;
private TabPane tpAppPane;
private Tab tabCustomers;
private ScrollPane spCustomerEditor;
private Tab tabAppointments;
private ScrollPane spAppointmentEditor;
private MainApp mainApp;
private static AppViewController instance;
private static AppointmentViewController appointmentViewController = AppointmentViewController.getInstance();
private static CustomerViewController customerViewController = CustomerViewController.getInstance();
private static DataViewController dataViewController;
private AppViewController() {
initialize();
}
public static AppViewController getInstance() {
if (instance == null) {
new AppViewController();
}
return instance;
}
/**
* Called to initialize a controller after its root element has been
* completely processed.
**/
public void initialize() {
instance = this;
this.rootPane = new BorderPane();
this.menuBar = new MenuBar();
this.fileMenu = new Menu("_File");
this.editMenu = new Menu("_Edit");
this.reportMenu = new Menu("_Report");
this.helpMenu = new Menu("_Help");
this.closeMenuItem = new MenuItem("Close");
this.copyMenuItem = new MenuItem("Copy");
this.monthlyAppointmentReportMenuItem = new MenuItem("Monthly Appointment Report");
this.consultantScheduleMenuItem = new MenuItem("Consultant Schedule Report");
this.customersByCountryMenuItem = new MenuItem("Customers by Country Report");
this.aboutMenuItem = new MenuItem("About");
this.vbAppView = new VBox();
this.tpAppPane = new TabPane();
this.tabCustomers = new Tab("Customers");
this.tabCustomers.setClosable(false);
this.spCustomerEditor = new ScrollPane();
this.tabAppointments = new Tab("Appointments");
this.tabAppointments.setClosable(false);
this.spAppointmentEditor = new ScrollPane();
// populate menus and menuBar and add them to top pane
this.fileMenu.getItems().setAll(closeMenuItem);
this.fileMenu.setMnemonicParsing(true);
this.editMenu.getItems().setAll(copyMenuItem);
this.editMenu.setMnemonicParsing(true);
this.reportMenu
.getItems()
.setAll(monthlyAppointmentReportMenuItem, consultantScheduleMenuItem, customersByCountryMenuItem);
this.reportMenu.setMnemonicParsing(true);
this.helpMenu.getItems().setAll(aboutMenuItem);
this.helpMenu.setMnemonicParsing(true);
this.menuBar.getMenus().addAll(fileMenu, editMenu, reportMenu, helpMenu);
this.rootPane.setTop(menuBar);
// populate scroll panes with included views
this.spAppointmentEditor.setContent(getAppointmentView());
this.spCustomerEditor.setContent(getCustomerView());
// populate tab panes and controllers and add them to the center pane
this.tabAppointments.setContent(spAppointmentEditor);
this.tabCustomers.setContent(spCustomerEditor);
this.tpAppPane.getTabs().addAll(tabAppointments, tabCustomers);
vbAppView.getChildren().addAll(tpAppPane);
this.rootPane.setCenter(vbAppView);
// add data view to bottom pane
this.rootPane.setBottom(AppointmentViewController.getDataView());
setupEventHandlers(this);
}
private void setupEventHandlers(AppViewController appViewController) {
this.tabCustomers.setOnSelectionChanged((event -> {
if (tabCustomers.isSelected()) {
// Change to Customer View
setCustomerView();
} else {
setAppointmentView();
}
}));
this.tabAppointments.setOnSelectionChanged(event -> {
if (tabAppointments.isSelected()) {
setAppointmentView();
} else {
setCustomerView();
}
});
this.closeMenuItem.setOnAction(event -> quitApp());
this.tpAppPane.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if(newValue.getText().toLowerCase().equals("Customer".toLowerCase())){
setCustomerView();
}
if (newValue.getText().toLowerCase().equals("Appointments".toLowerCase())){
setAppointmentView();
}
});
}
private void setCustomerView() {
CustomerViewController customerViewController = CustomerViewController.getInstance();
setDataView(customerViewController.getDataViewController().tabPane);
customerViewController.getGpCustomerEditor().getChildren().filtered(node -> toggleTextFields(node, true));
}
private void setAppointmentView() {
AppointmentViewController controller = AppointmentViewController.getInstance();
setDataView(controller.getDataViewController().tabPane);
controller.getGpAppointmentEditor().getChildren().filtered(node -> toggleTextFields(node, true));
}
/***
* Sets whether text fields are enabled or disabled
* true = disable Text Fields
* false = enable Text Fields
* #param node the child nodes of the editor
* #param disabled whether to disable or enable the text fields
* #return whether node was affected or not
*/
public static boolean toggleTextFields(Node node, boolean disabled) {
if (node instanceof TextField) {
((TextField) node).setEditable(!disabled);
node.setDisable(disabled);
return true;
}
return false;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
private void quitApp() {
Platform.exit();
}
public Parent getBorderPane() {
return rootPane;
}
public TabPane getTpAppPane() {
return tpAppPane;
}
public Tab getTabCustomers() {
return tabCustomers;
}
public Tab getTabAppointments() {
return tabAppointments;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("AppViewController{");
sb.append("\nrootPane=").append(rootPane);
sb.append(",\n menuBar=").append(menuBar);
sb.append(",\n fileMenu=").append(fileMenu);
sb.append(",\n editMenu=").append(editMenu);
sb.append(",\n reportMenu=").append(reportMenu);
sb.append(",\n helpMenu=").append(helpMenu);
sb.append(",\n closeMenuItem=").append(closeMenuItem);
sb.append(",\n copyMenuItem=").append(copyMenuItem);
sb.append(",\n monthlyAppointmentReportMenuItem=").append(monthlyAppointmentReportMenuItem);
sb.append(",\n consultantScheduleMenuItem=").append(consultantScheduleMenuItem);
sb.append(",\n customersByCountryMenuItem=").append(customersByCountryMenuItem);
sb.append(",\n aboutMenuItem=").append(aboutMenuItem);
sb.append(",\n vbAppView=").append(vbAppView);
sb.append(",\n tpAppPane=").append(tpAppPane);
sb.append(",\n tabCustomers=").append(tabCustomers);
sb.append(",\n spCustomerEditor=").append(spCustomerEditor);
sb.append(",\n tabAppointments=").append(tabAppointments);
sb.append(",\n spAppointmentEditor=").append(spAppointmentEditor);
sb.append(",\n dataViewController=").append(dataViewController);
sb.append("\n}");
return sb.toString();
}
public void setDataViewController(DataViewController dataViewController) {
this.dataViewController = dataViewController;
}
public DataViewController getDataViewController() {
return dataViewController;
}
}
And the AppointmentView:
private TableView<AppointmentView> tvAppointments = new TableView<>();
private TableColumn<AppointmentView, String> tcTitle = new TableColumn<>("Title");
private TableColumn<AppointmentView, String> tcDescription = new TableColumn<>("Description");
private TableColumn<AppointmentView, String> tcLocation = new TableColumn<>("Location");
private TableColumn<AppointmentView, String> tcContact = new TableColumn<>("Contact");
private TableColumn<AppointmentView, String> tcUrl = new TableColumn<>("URL");
private TableColumn<AppointmentView, String> tcCustomerName = new TableColumn<>("Customer Name");
private TableColumn<AppointmentView, ZonedDateTime> tcStart = new TableColumn<>("Start Time");
private TableColumn<AppointmentView, ZonedDateTime> tcEnd = new TableColumn<>("End Time");
private TableColumn<AppointmentView, ZonedDateTime> tcCreateDate = new TableColumn<>("Created Date");
private TableColumn<AppointmentView, String> tcCreatedBy = new TableColumn<>("Created By");
private TableColumn<AppointmentView, Timestamp> tcLastUpdate = new TableColumn<>("Last Updated");
---- snip ----
this.tcTitle.setCellValueFactory(new PropertyValueFactory<>("title"));
this.tcTitle.setVisible(true);
this.tcTitle.setMinWidth(50);
this.tcCustomerName.setCellValueFactory(new PropertyValueFactory<>("customerName"));
this.tcCustomerName.setVisible(true);
this.tcCustomerName.setMinWidth(40);
this.tcDescription.setCellValueFactory(new PropertyValueFactory<>("description"));
this.tcDescription.setVisible(true);
this.tcDescription.setMinWidth(100);
this.tcLocation.setCellValueFactory(new PropertyValueFactory<>("location"));
this.tcLocation.setVisible(true);
this.tcLocation.setMinWidth(40);
this.tcContact.setCellValueFactory(new PropertyValueFactory<>("contact"));
this.tcContact.setVisible(true);
this.tcContact.setMinWidth(40);
this.tcUrl.setCellValueFactory(new PropertyValueFactory<>("url".toUpperCase()));
this.tcUrl.setVisible(true);
this.tcUrl.setMinWidth(40);
this.tcStart.setCellValueFactory(new PropertyValueFactory<>("start"));
this.tcStart.setVisible(true);
this.tcStart.setMinWidth(40);
this.tcEnd.setCellValueFactory(new PropertyValueFactory<>("end"));
this.tcEnd.setVisible(true);
this.tcEnd.setMinWidth(40);
this.tcCreateDate.setCellValueFactory(new PropertyValueFactory<>("createDate"));
this.tcCreateDate.setVisible(true);
this.tcCreateDate.setMinWidth(40);
this.tcCreatedBy.setCellValueFactory(new PropertyValueFactory<>("createdBy"));
this.tcCreatedBy.setVisible(true);
this.tcCreatedBy.setMinWidth(40);
this.tcLastUpdate.setCellValueFactory(new PropertyValueFactory<>("lastUpdate"));
this.tcLastUpdate.setVisible(true);
this.tcLastUpdate.setMinWidth(40);
this.tvAppointments = new TableView<>();
this.tvAppointments.setItems(appointmentViews);
this.tvAppointments.getColumns().addAll(
tcTitle,
tcDescription,
tcLocation,
tcContact,
tcUrl,
tcCustomerName,
tcStart,
tcEnd,
tcCreateDate,
tcCreatedBy,
tcLastUpdate);
this.lvListView = new ListView<>();
this.lvListView.setItems(appointmentViews);
this.dataViewController.setTableView(this.tvAppointments);
this.dataViewController.setLblListView(new Label("Appointment List"));
this.dataViewController.setListView(this.lvListView);
this.dataViewController.setLblTableView(new Label("Appointments"));
And the base DataViewController that I'm trying to manipulate:
public class DataViewController extends TabPane {
// private static DataViewController instance;
public TabPane tabPane;
private Tab tabTableView;
private Tab tabListView;
private VBox vbListView;
private VBox vbTableView;
private Label lblListView;
private Label lblTableView;
protected ScrollPane spListView;
protected ScrollPane spTableView;
private ListView<?> listView;
private TableView<?> tableView;
private MainApp mainApp;
public DataViewController() {
initialize();
}
/* public static DataViewController getInstance(){
if(instance == null){
new DataViewController();
}
return instance;
}*/
/**
* Called to initialize a controller after its root element has been
* completely processed.
*
*/
public void initialize() {
// this.instance = this;
this.tabPane = new TabPane();
this.tabPane.setPrefHeight(250.0);
this.tabPane.setMaxHeight(400.0);
this.tabPane.setMaxWidth(Integer.MAX_VALUE);
this.tabTableView = new Tab("Table View");
this.tabTableView.setClosable(false);
this.tabListView = new Tab("List View");
this.tabListView.setClosable(false);
this.spListView = new ScrollPane();
this.spTableView = new ScrollPane();
this.lblListView = new Label("List View");
this.lblTableView = new Label("Table View");
this.vbListView = new VBox();
this.vbTableView = new VBox();
this.listView = new ListView<>();
this.tableView = new TableView<>();
this.vbListView.getChildren().setAll(this.lblListView, this.listView);
this.spListView.setContent(this.listView);
this.tabListView.setContent(this.spListView);
this.vbTableView.getChildren().setAll(this.lblTableView, this.spTableView);
this.spTableView.setContent(this.tableView);
this.tabTableView.setContent(vbTableView);
this.tabPane.getTabs().setAll(tabListView, tabTableView);
}
public Label getLblListView() {
return lblListView;
}
public void setLblListView(Label lblListView) {
this.lblListView = lblListView;
}
public Label getLblTableView() {
return lblTableView;
}
public void setLblTableView(Label lblTableView) {
this.lblTableView = lblTableView;
}
public ListView<?> getListView() {
return listView;
}
public void setListView(ListView<?> listView) {
this.listView = listView;
}
public TableView<?> getTableView() {
return tableView;
}
public void setTableView(TableView<?> tableView) {
this.tableView = tableView;
}
public void setMainApp(MainApp mainApp){
this.mainApp = mainApp;
}
/* public static DataViewController getInstance() {
if (instance == null){
instance = new DataViewController();
}
return instance;
}*/
#Override
public String toString() {
return new StringBuilder()
.append("DataViewController{")
.append("\ntabPane=")
.append(tabPane)
.append(", \ntabTableView=")
.append(tabTableView)
.append(", \ntabListView=")
.append(tabListView)
.append(", \nvbListView=")
.append(vbListView)
.append(", \nvbTableView=")
.append(vbTableView)
.append(", \nlblListView=")
.append(lblListView.getText())
.append(", \nlblTableView=")
.append(lblTableView.getText())
.append(", \nspListView=")
.append(spListView)
.append(", \nspTableView=")
.append(spTableView)
.append(", \nlistView=")
.append(listView.getItems())
.append(", \ntableView=")
.append(tableView.getColumns())
.append("\n}")
.toString();
}
}
As mentioned, I put in a few toString calls and implementations and I keep seeing the objects in DataViewController per this:
listView=[AppointmentView{createdDate=2017-09-02T00:00-07:00[America/Los_Angeles], createdBy='test1', titleProperty=StringProperty [value: Meet with Amari], descriptionProperty=StringProperty [value: Meeting WR of the Raiders], locationProperty=StringProperty [value: Raiders HQ, Alameda], contactProperty=StringProperty [value: Jack DelRio], urlProperty=StringProperty [value: raiders.com], customerName=StringProperty [value: Amari Cooper], startProperty=ObjectProperty [value: 2017-09-04T16:00-07:00[America/Los_Angeles]], endProperty=ObjectProperty [value: 2017-09-04T16:15-07:00[America/Los_Angeles]], lastUpdated=ObjectProperty [value: 2017-09-02T23:07-07:00[America/Los_Angeles]]}, AppointmentView{createdDate=2017-09-02T00:00-07:00[America/Los_Angeles], createdBy='test1', titleProperty=StringProperty [value: Meet with Amari], descriptionProperty=StringProperty [value: Meeting WR of the Raiders], locationProperty=StringProperty [value: Raiders HQ, Alameda], contactProperty=StringProperty [value: Jack DelRio], urlProperty=StringProperty [value: raiders.com], customerName=StringProperty [value: Amari Cooper], startProperty=ObjectProperty [value: 2017-09-04T16:00-07:00[America/Los_Angeles]], endProperty=ObjectProperty [value: 2017-09-04T16:15-07:00[America/Los_Angeles]], lastUpdated=ObjectProperty [value: 2017-09-02T23:07-07:00[America/Los_Angeles]]}],
tableView=[javafx.scene.control.TableColumn#6167e82, javafx.scene.control.TableColumn#50658769, javafx.scene.control.TableColumn#f65aae1, javafx.scene.control.TableColumn#2d5ab3ab, javafx.scene.control.TableColumn#180d2aec, javafx.scene.control.TableColumn#64afb84b, javafx.scene.control.TableColumn#463f349d, javafx.scene.control.TableColumn#3e80101a, javafx.scene.control.TableColumn#4fab076c, javafx.scene.control.TableColumn#565f8332, javafx.scene.control.TableColumn#697bdeb8]
And here's the MainApp method that's calling it:
private void initLayout() {
// rootPane = new BorderPane();
appointmentViewController = AppointmentViewController.getInstance();
appointmentView = appointmentViewController.apAppointmentView;
appointmentViewController.setMainApp(this);
dataViewController = appointmentViewController.getDataViewController();
dataView = dataViewController.tabPane;
dataViewController.setMainApp(this);
customerViewController = CustomerViewController.getInstance();
customerView = customerViewController.apCustomerView;
customerViewController.setMainApp(this);
appViewController = AppViewController.getInstance();
appView = appViewController.getBorderPane();
appViewController.setMainApp(this);
appViewController.setDataViewController(appointmentViewController.getDataViewController());
System.out.println(this.dataViewController);
System.out.println(this.dataView);
System.out.println(appointmentViewController.toString());
System.out.println(customerViewController.toString());
System.out.println(appViewController.toString());
rootPane = (BorderPane) appView;
scene = new Scene(rootPane);
scene.getStylesheets().add("/styles/Styles.css");
primaryStage.setScene(scene);
primaryStage.show();
}
I've setup the CellValueFactories,etc. What am I missing here?
This is how the UI is shown:
In DataViewController the scene structure is initialized from the constructor. Using any of the setters in this class modifies the fields, it does not modify the scene in any way leaving the old empty ListView in the scene but printing the new one containing items from the toString method.

GWT CellTree inside a DataGrid does not react to mouse-clicks

I have put a GWT-CellTree in a DataGrid. It works except for one thing: When clicking on the tree-expand-icon, nothing happens. I have tried to minimize the
code needed to reproduce the problem...
How can this be fixed ?
best regards, Magnus
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
DataGrid grid= (DataGrid) new NodesGrid().getTable();
grid.setWidth("100%");
SimpleLayoutPanel slp = new SimpleLayoutPanel();
slp.add(grid);
RootLayoutPanel.get().add(slp);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class NodesGrid {
private AbstractCellTable<Node> table = new DataGrid<>();
private Column nameColumn;
private Column<Node, String> showBlocksColumn;
private final Set<Integer> showBlocks = new HashSet<>();
public Column getNameColumn() {
return nameColumn;
}
public AbstractCellTable<Node> getTable() {
return table;
}
public NodesGrid() {
table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
table.setWidth("100%");
CustomCellTableBuilder c = new CustomCellTableBuilder(this, table);
table.setTableBuilder(c);
Node nodes = new Node();
nodes.setName("hello");
nodes.setId(123);
Node n2 = new Node();
n2.setName("testing");
nodes.getBlocks().add(n2);
ListDataProvider<Node> dataProvider = new ListDataProvider<>();
dataProvider.addDataDisplay(table);
List<Node> list = dataProvider.getList();
list.add(nodes);
addShowBlocks();
nameColumn = getSorter(list, "Name", Comparator.comparing(Node::getName), Node::getName);
}
private Column getSorter(List<Node> list,
String name,
Comparator<Node> cmp,
Function<Node, String> supplier) {
TextColumn<Node> column = new TextColumn<Node>() {
#Override
public String getValue(Node object) {
return supplier.apply(object);
}
};
table.addColumn(column, name);
column.setSortable(true);
ColumnSortEvent.ListHandler<Node> columnSortHandler = new ColumnSortEvent.ListHandler<>(list);
columnSortHandler.setComparator(column, cmp);
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(column);
return column;
}
public Column<Node, String> getShowBlocksColumn() {
return showBlocksColumn;
}
public Set<Integer> getShowBlocks() {
return showBlocks;
}
void addShowBlocks() {
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>)");
return sb.toSafeHtml();
}
};
showBlocksColumn = new Column<Node, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(Node node) {
if (showBlocks.contains(node.getId())) {
return "hide blocks";
} else {
return "show blocks";
}
}
};
showBlocksColumn.setFieldUpdater(new FieldUpdater<Node, String>() {
#Override
public void update(int index, Node node, String value) {
if (showBlocks.contains(node.getId())) {
showBlocks.remove(node.getId());
} else {
showBlocks.add(node.getId());
}
table.redrawRow(index);
}
});
table.addColumn(showBlocksColumn);
table.setColumnWidth(0, 10, Style.Unit.EM);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import java.util.ArrayList;
import java.util.List;
public class NodesTree {
private CellTree tree;
public NodesTree(Node node) {
TreeViewModel model = new CustomTreeModel(node);
tree = new CellTree(model, null);
tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
TreeNode rootNode = tree.getRootTreeNode();
openAll(rootNode);
}
private static class TopLevel {
private final String name;
private List<Node> blocks = new ArrayList<>();
public TopLevel(String name) {
this.name = name;
}
public TopLevel(String name, List<Node> blocks) {
this.name = name;
this.blocks = blocks;
}
public String getName() {
return name;
}
public List<Node> getBlocks() {
return blocks;
}
}
private static class CustomTreeModel implements TreeViewModel {
private final List<TopLevel> topLevels;
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<>();
public CustomTreeModel(Node node) {
topLevels = new ArrayList<>();
{
TopLevel blocksNode = new TopLevel("Blocks", new ArrayList(node.getBlocks()));
topLevels.add(blocksNode);
}
{
TopLevel outgoing = new TopLevel("Outgoing");
topLevels.add(outgoing);
}
{
TopLevel incoming = new TopLevel("Incoming");
topLevels.add(incoming);
}
}
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
ListDataProvider<TopLevel> dataProvider
= new ListDataProvider<>(
topLevels);
Cell<TopLevel> cell = new AbstractCell<TopLevel>() {
#Override
public void render(Context context, TopLevel value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof TopLevel) {
// LEVEL 1.
ListDataProvider<Node> dataProvider = new ListDataProvider<>(((TopLevel) value).getBlocks());
Cell<Node> cell = new AbstractCell<Node>() {
#Override
public void render(Context context, Node value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped("(" + value.getName() + ")");
}
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof Node) {
// LEVEL 2 - LEAF.
String params = "test";
ArrayList<String> str = new ArrayList<>();
str.add(params);
ListDataProvider<String> dataProvider = new ListDataProvider<>(str);
return new DefaultNodeInfo<>(dataProvider, new TextCell(), selectionModel, null);
}
return null;
}
public boolean isLeaf(Object value) {
if (value instanceof String) {
return true;
}
return false;
}
}
private void openAll(TreeNode rootNode) {
if (rootNode == null) return;
for (int i = 0; i < rootNode.getChildCount(); i++) {
TreeNode node = rootNode.setChildOpen(i, true);
openAll(node);
}
}
public Widget getWidget() {
return tree;
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.AbstractCellTableBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.view.client.SelectionModel;
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Node> {
NodesGrid nodesGrid;
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
/**
* Construct a new table builder.
*
* #param cellTable the table this builder will build rows for
*/
public CustomCellTableBuilder(NodesGrid nodesGrid, AbstractCellTable<Node> cellTable) {
super(cellTable);
this.nodesGrid = nodesGrid;
AbstractCellTable.Style style = cellTable.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
#Override
protected void buildRowImpl(Node rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super Node> selectionModel = cellTable.getSelectionModel();
boolean isSelected =
(selectionModel == null || rowValue == null) ? false : selectionModel
.isSelected(rowValue);
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
buildRow(row, rowValue, cellStyles, nodesGrid.getShowBlocksColumn());
buildRow(row, rowValue, cellStyles, nodesGrid.getNameColumn());
row.endTR();
if (nodesGrid.getShowBlocks().contains(rowValue.getId())) {
buildBlockRow(rowValue, cellStyles);
}
}
void buildRow(TableRowBuilder row, Node rowValue, String cellStyles, Column column) {
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
renderCell(td, createContext(0), column, rowValue);
td.endTD();
}
private void buildBlockRow(Node rowValue, String cellStyles) {
TableRowBuilder row = startRow();
buildCell(rowValue, cellStyles, row);
row.endTR();
}
private void buildCell(Node rowValue, String cellStyles, TableRowBuilder row) {
NodesTree hw = new NodesTree(rowValue);
TableCellBuilder td = row.startTD().colSpan(5);
td.className(cellStyles);
DivBuilder div = td.startDiv();
String t = hw.getWidget().getElement().getInnerHTML();
div.html(SafeHtmlUtils.fromTrustedString(t));
div.end();
td.endTD();
}
}
package com.raybased.gwt.configtool.client.grid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Node implements Serializable {
String name;
List<Node> blocks = new ArrayList<>();
String params;
int id;
public Node() {
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Node> getBlocks() {
return blocks;
}
}

JavaFX Table searching with optional column

I have a tableview that i populate using an observablelist, ObservableList<Member>. The some attributes in Member object are optional, so the table cell for that row will be empty.
I have implemented FilteredList<Member> and SortedList<Member> although when i search, because of those null values in some cells, a java.lang.NullPointerException is thrown. I have no idea on how to solve this problem.
The following is SSCCE, that demonstrate my problem
package com.yunusfx.javafxcustomcontrols.yunusreproduceproblem;
import javafx.application.Application;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableSearch extends Application{
private TableView<Member> tv = new TableView();
private TextField tfSearch = new TextField();
ObservableList<Member> memberList = FXCollections.observableArrayList();
ListProperty<Member> memberListProperty = new SimpleListProperty<>();
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage primaryStage) throws Exception {
TableColumn<Member, String> name = createNameColumn();
TableColumn<Member, Integer> age = createAgeColumn();
TableColumn<Member, String> account = createAccountColumn();
TableColumn<Member, String> location = createLocationColumn();
tfSearch.setPromptText("Search here");
tv.getColumns().addAll(name, age, account, location);
memberListProperty.set(memberList);
tv.itemsProperty().bindBidirectional(memberListProperty);
tv.setItems(memberListProperty);
setData();
FilteredList<Member> filteredData = new FilteredList<>(memberList, p -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(Member -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (Member.getName().toLowerCase().contains(lowerCaseFilter)) {
return true;
// } else if(Member.getAge().toLowerCase().contains(lowerCaseFilter)){
// No idea how to search if is integer
// return true;
}else if(Member.getLocation().toString().toLowerCase().contains(lowerCaseFilter)){
return true;
}else if(Member.getAccount().toLowerCase().contains(lowerCaseFilter)){
return true;
}
return false;
});
});
SortedList<Member> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tv.comparatorProperty());
tv.setItems(sortedData);
BorderPane borderPane = new BorderPane();
borderPane.setTop(tfSearch);
borderPane.setCenter(tv);
Scene scene = new Scene(borderPane, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private TableColumn createNameColumn() {
TableColumn<Member, String> colName = new TableColumn("Name");
colName.setMinWidth(25);
colName.setId("colName");
colName.setCellValueFactory(new PropertyValueFactory("name"));
return colName;
}
private TableColumn createAgeColumn() {
TableColumn<Member, Integer> colAge = new TableColumn("Age");
colAge.setMinWidth(25);
colAge.setId("colAge");
colAge.setCellValueFactory(new PropertyValueFactory("age"));
return colAge;
}
private TableColumn createAccountColumn() {
TableColumn<Member, String> colAccount = new TableColumn("Account");
colAccount.setMinWidth(25);
colAccount.setId("colAccount");
colAccount.setCellValueFactory(new PropertyValueFactory("account"));
return colAccount;
}
private TableColumn createLocationColumn() {
TableColumn<Member, String> colAccount = new TableColumn("Location");
colAccount.setMinWidth(25);
colAccount.setId("colLocation");
colAccount.setCellValueFactory(new PropertyValueFactory("location"));
return colAccount;
}
private void setData(){
Member m = new Member();
m.setAccount("we123");
m.setAge(456);
m.setLocation("Nairobi");
m.setName("Member 1");
memberList.add(m);
Member m1 = new Member();
m1.setAccount("OP5623");
m1.setAge(321);
m1.setLocation("Mombasa");
m1.setName("Doe");
memberList.add(m1);
Member m2 = new Member();
m2.setAge(569);
m2.setLocation("Meru");
m2.setName("John");
memberList.add(m2);
Member m3 = new Member();
m3.setAccount("YGTR665");
m3.setAge(666);
m3.setLocation("Eldoret");
m3.setName("Arif");
memberList.add(m3);
Member m4 = new Member();
m4.setAccount("BHJI58966");
m4.setAge(397);
m4.setName("Yunus");
memberList.add(m4);
}
public class Member {
private int id;
private String name;
private Integer age;
private String account;
private String location;
public Member(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
}
Clarification
By optional i mean some attributes in Member object might not have been set hence its table cell will be empty
I wasn't able to add age column to be searchable
Based on James_D's comment i was able to make search work but first check if value is null for optional attributes. For integer, convert it to string then use the string value. The important point is, the code is only dealing with actual data.
Following is what i updated:
FilteredList<Member> filteredData = new FilteredList<>(memberList, p -> true);
tfSearch.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(Member -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (Member.getName().toLowerCase().contains(lowerCaseFilter)) {
return true;
} else if(Integer.toString(Member.getAge()).contains(lowerCaseFilter)){
return true;
}else if(Member.getLocation() != null && Member.getLocation().toLowerCase().contains(lowerCaseFilter)){
return true;
}else if(Member.getAccount() != null && Member.getAccount().toLowerCase().contains(lowerCaseFilter)){
return true;
}
return false;
});
});

URL issue in Facebook in BlackBerry

I have integrated Facebook in my app and trying to share some content.When I call FaceBookMain() ,it shows error like :
"Success
SECURITY WARNINNG:Please treat the URL above as you would your password and do not share it with anyone."
Sometimes this error comes after login with Facebook in browser(Webview) otherwise it comes just after clicking on share button.
Most important thing here is ,I am not facing this problem in simulator.Sharing with Facebook is working properly in Simulator but not in Device.
I am adding some class files with it:
Here is FacebookMain.java class:
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.UiApplication;
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID = "406758776102494";//"533918076671162" ;
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public static boolean isFacebookScreen = false;
public FacebookMain(String postMessge) {
this.postMessage= postMessge;
isFacebookScreen = true;
checkPermissions();
fbc=new FacebookContext(NEXT_URL, APPLICATION_ID);
loginScreen = new LoginScreen(fbc,"KingdomConnect: "+postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
/*ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);*/
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {}
}
It is Facebook.java class:
public class Facebook {
protected Logger log = Logger.getLogger(getClass());
public static String API_URL = "https://graph.facebook.com";
public Facebook() {
}
public static Object read(String path, String accessToken) throws FacebookException {
return read(path, null, accessToken);
}
public static Object read(String path, Parameters params, String accessToken) throws FacebookException {
Hashtable args = new Hashtable();
args.put("access_token", accessToken);
args.put("format", "JSON");
if ((params != null) && (params.getCount() > 0)) {
Enumeration paramNamesEnum = params.getParameterNames();
while (paramNamesEnum.hasMoreElements()) {
String paramName = (String) paramNamesEnum.nextElement();
String paramValue = params.get(paramName).getValue();
args.put(paramName, paramValue);
}
}
try {
StringBuffer responseBuffer = HttpClient.getInstance().doGet(API_URL + '/' + path, args);
if (responseBuffer.length() == 0) {
throw new Exception("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Throwable t) {
t.printStackTrace();
throw new FacebookException(t.getMessage());
}
}
public static Object write(String path, Object object, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
try {
JSONObject jsonObject = (JSONObject) object;
Enumeration keysEnum = jsonObject.keys();
while (keysEnum.hasMoreElements()) {
String key = (String) keysEnum.nextElement();
Object val = jsonObject.get(key);
if (!(val instanceof JSONObject)) {
data.put(key, val.toString());
}
}
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
public static Object delete(String path, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
data.put("method", "delete");
try {
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
}
And it is BrowserScreen.class:
public class BrowserScreen extends ActionScreen {
// int[] preferredTransportTypes = { TransportInfo.TRANSPORT_TCP_CELLULAR, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_BIS_B };
int[] preferredTransportTypes = TransportInfo.getAvailableTransportTypes();//{ TransportInfo.TRANSPORT_BIS_B };
ConnectionFactory cf;
BrowserFieldConfig bfc;
BrowserField bf;
String url;
public BrowserScreen(String pUrl) {
super();
url = pUrl;
cf = new ConnectionFactory();
cf.setPreferredTransportTypes(preferredTransportTypes);
bfc = new BrowserFieldConfig();
bfc.setProperty(BrowserFieldConfig.ALLOW_CS_XHR, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.MDS_TRANSCODING_ENABLED, Boolean.FALSE);
bfc.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
bfc.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
// bfc.setProperty(BrowserFieldConfig.CONNECTION_FACTORY, cf);
bf = new BrowserField(bfc);
}
public void browse() {
show();
fetch();
}
public void show() {
add(bf);
}
public void fetch() {
bf.requestContent(url);
}
public void hide() {
delete(bf);
}
}
If any body has any clue or want some more related code to get it,please let me know.
do not use secure connection. use http instead of https.
you can refer here
same problem is presented in stackoverflow
facebook warning