Java - Exception PropertyUtilsBean.setIndexedProperty - apache-commons-beanutils

public class TestBean {
private String[] array;
public String[] getArray() {
return array;
}
public void setArray(String[] array) {
this.array = array;
}
}
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilTest {
public static void main(String[] args) {
TestBean bean = new TestBean();
try {
BeanUtils.setProperty(bean, "array[0]", "zero");
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
While running the code the following exception is getting
java.lang.NullPointerException
at org.apache.commons.beanutils.PropertyUtilsBean.setIndexedProperty(PropertyUtilsBean.java:1414)
at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1016)
at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313)
at BeanUtilTest.main(BeanUtilTest.java:10)
The array size will be increase while run time. So I don't want as a fixed size array. Array size should be defined at runtime.

You need to initialize the array or set the array using
BeanUtils.setProperty(bean, "array", array);
and then use following operation to set the value
BeanUtils.setProperty(bean, "array[0]", "zero");
Array size will not increase during runtime

Related

UI updates are getting blocked by future.get() in javafx

I have a function which is supposed to return a list from the result of a Task API.
#Override
public List performQuery(boolean isPaginationQuery, boolean isSortingQuery {
try {
TaskImpl taskImpl = new TaskImpl(isPaginationQuery,
isSortingQuery);
queryExecutor.submit(taskImpl).get();
return taskImpl.get();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Inner class which performs the updates
private class TaskImpl extends Task<List> {
private boolean isPaginationQuery, isSortingQuery;
public TaskImpl(boolean isPaginationQuery, boolean isSortingQuery) {
this.isPaginationQuery = isPaginationQuery;
this.isSortingQuery = isSortingQuery;
}
#Override
protected List call() throws Exception {
Platform.runLater(() -> {
loaderContainer.setVisible(true);
loaderContainer.toFront();
});
HSession hSession = new HSession();
TaskInfoDao taskInfoDao = new TaskInfoDaoImpl(hSession.getSession(), currentConnection.getConnectionId());
if (!isPaginationQuery && !isSortingQuery) {
paginator.setTotal(taskInfoDao.getTaskInfoWithFiltersCount(paginator.getFilterMap(), false));
}
Stream<TaskInfo> resultStream = taskInfoDao.getTaskInfoWithFilters(paginator.getFilterMap(), false,
paginator.getStartIndex() * paginator.getPageSize(),
paginator.getPageSize() * paginator.getPageGap());
List<TaskInfoTableView> data = createData(resultStream);
hSession.close();
return data;
}
#Override
protected void succeeded() {
super.succeeded();
try {
//set the pagination if the task is complete
//and it is not a pagination query
if (!isPaginationQuery) {
((TaskInfoViewController) uiController).setPagination(
FXCollections.observableArrayList(get()));
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
#Override
protected void cancelled() {
super.cancelled();
updateMessage("Cancelled!");
}
#Override
protected void failed() {
super.failed();
updateMessage("Failed!");
}
}
performQuery function calls the thread and waits for its result.
The loader is being displayed from inside the TaskImpl class using Platform.runLater.
But the loader does not appear until the task has finished i.e. loader appears after the completion of call() function's execution.
When i remove the taskImpl.get() the loader works fine.
Any help is appreciated.
P.S. : Under any case, I need the result of the Task API outside the Inner class( outside TaskImpl )
First of all, it seems like you are not very familiar with asynchronous programming. Having performQuery() to return a List shows that you are expecting to run this synchronously - there is no way for you to return results before you get the results. This is exactly why you are freezing your UI.
The important thing to understand about asynchronous programming is, you would start doing something (i.e. a task) in another thread, and return immediately. When there is result returned from the task, you switch back to the UI (JavaFX Application) thread to update it. You can see this as event-driven approach.
Therefore, for your case, you should directly update the list (the list which you are returning in performQuery()) in the succeeded() method that you have overridden in TaskImpl class.
If the list that you should be updating is not in the scope of TaskImpl, then you can the functional interfaces in java.util.function package to do it for you. This means that you would create that functional interface object at the right scope, and pass in into TaskImpl during object construction, and call that interface in succeeded().
Update
If I assume this is what calls performQuery():
public class MyController {
#FXML
TableView<Foo> tableView;
public void initialize() {
List result = queryController.performQuery(true, true);
tableView.getItems().addAll(result);
}
}
Then, I would probably do something like this:
public class MyController {
#FXML
TableView<Foo> tableView;
public void initialize() {
List result = queryController.performQuery(true, true, list -> tableView.getItems.addAll(list));
}
}
public class QueryController {
#Override
public void performQuery(boolean isPaginationQuery, boolean isSortingQuery, java.util.function.Consumer<List> onQuerySucceeded) {
try {
TaskImpl taskImpl = new TaskImpl(isPaginationQuery,
isSortingQuery, onQuerySucceeded);
queryExecutor.submit(taskImpl);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
private class TaskImpl extends Task<List> {
private final java.util.function.Consumer<List> onQuerySucceeded;
public TaskImpl(boolean isPaginationQuery, boolean isSortingQuery, java.util.function.Consumer<List> onQuerySucceeded) {
this.isPaginationQuery = isPaginationQuery;
this.isSortingQuery = isSortingQuery;
this.onQuerySucceeded = onQuerySucceeded;
}
#Override
protected void succeeded() {
super.succeeded();
// Not sure what the original codes are doing.
try {
//set the pagination if the task is complete
//and it is not a pagination query
if (!isPaginationQuery) {
((TaskInfoViewController) uiController).setPagination(
FXCollections.observableArrayList(get()));
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// This is what is being added in
onQuerySucceeded.accept(this.getValue());
}
}

getting error on createObject

i am getting
StartSensor Attempt to invoke virtual method 'void io.realm.ProxyState.setConstructionFinished()' on a null object reference
i try to create a new object with primarykey inside application class.
primarykeyFactory works it set the new key to "1" the database is empty at this moment.
public class SensorRecord extends MainApplication {
private final static String TAG = SensorRecord.class.getSimpleName();
private Realm mRealm;
public SensorRecord() {
Realm.init(this);
mRealm = getInstance(getRealmConfig());
}
public void StartSensor(long startTime) {
long newprimekey = PrimaryKeyFactory.getInstance().nextKey(SensorData.class);
try {
mRealm.beginTransaction();
SensorData mSensorData = mRealm.createObject(SensorData.class, newprimekey);
mSensorData.setstarted_at(startTime);
mRealm.commitTransaction();
mRealm.close();
} catch (Exception e) {
Log.v(TAG, "StartSensor " + e.getMessage());
}
}}
my main application class which init the realm config
public class MainApplication extends RealmBaseApplication {
private final static String TAG = MainApplication.class.getSimpleName();
Realm mRealm;
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
mRealm = getInstance(getRealmConfig());
initializePrimaryKeyFactory();
}
public void initializePrimaryKeyFactory() {
try {
Log.v(TAG, "Start PrimaryKeyFactory ");
PrimaryKeyFactory.getInstance().initialize(mRealm);
} catch (Exception e) {
Log.v(TAG, "initializePrimaryKeyFactory " + e.getMessage());
}
}}
and my realm config class
public abstract class RealmBaseApplication extends Application {
private RealmConfiguration realmConfiguration;
protected RealmConfiguration getRealmConfig() {
if (realmConfiguration == null) {
realmConfiguration = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.build();
}
Realm.setDefaultConfiguration(realmConfiguration);
return realmConfiguration;
}
protected void resetRealm() {
Realm.deleteRealm(getRealmConfig());
}}
kind regards
viktoria
ok fixed by myself. had add butterknife tonight. and with that i add apt to my build.gradle... i removed
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
apply plugin: 'com.neenbedankt.android-apt'
and replaced
apt 'com.jakewharton:butterknife-compiler:8.5.1'
with
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

Error Showing as Class Cast Exception while changing the value of combobox in Javafx

On selection of Tableview row, it display the data in the combobox,
i try to display the value in the comboxbox from tableview using this code.
private void showInputDetails(InputConfigurationModel ipmodel) {
if (ipmodel != null) {
cmbfiletype.setValue(ipmodel.getFiletype().toString());
}
My Inputconfiguartion Model class:
public class InputConfigurationModel {
public StringProperty filetype = new SimpleStringProperty();
public InputConfigurationModel(String filetype) {
this.filetype = new SimpleStringProperty(filetype);
}
public InputConfigurationModel() {
}
public String getFiletype() {
return filetype.get();
}
public void setFiletype(String value) {
filetype.set(value);
}
public StringProperty filetypeProperty()
{
return filetype;
}
// #Override
// public String toString() {
// return filetype.toString(); //To change body of generated methods, choose Tools | Templates.
// }
}
but if i try change the value of combobox for update it display error as
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to Clover.Converter.Model.ExtensionModel
i am trying to change the value in the combobox from this code
Loading the combobox value from this Loadfile method
public void LoadFile() {
try {
String sql = "select * from EXTENSION";
PreparedStatement ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
while (rs.next()) {
ExtensionModel extModel = new ExtensionModel();
filetypelstupdate_ip = FXCollections.observableArrayList(extModel);
String ext_type = rs.getString("EXT_TYPE");
String ext_name = rs.getString("EXT_NAME");
int ext_id=Integer.parseInt(rs.getString("EXT_ID"));
extModel.setExttype(ext_type);
extModel.setExtname(ext_name);
extModel.setExtid(ext_id);
cmbfiletype.getItems().addAll(filetypelstupdate_ip);
cmbfiletype.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ExtensionModel>() {
#Override
public void changed(ObservableValue<? extends ExtensionModel> observable, ExtensionModel oldValue, ExtensionModel newValue) {
aaa(newValue);
}
});
catch (Exception ex) {
ex.printStackTrace();
}
}
public void aaa(ExtensionModel exm){
if(cmbfiletype!=null)
{
txtextid.setText(exm.getExtid().toString());
System.out.println("txtextid"+txtextid);
}
}
i dont how to solve this error? tried everything but still coming class cast exception
my error is coming in LoadFile Method in this code first line
**cmbfiletype.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ExtensionModel>() {**
#Override
public void changed(ObservableValue<? extends ExtensionModel> observable, ExtensionModel oldValue, ExtensionModel newValue) {
aaa(newValue);
});
}
} catch (Exception e) {
e.printStackTrace();
}
First it display the value in the comboxbox from the tableview which is a string in INPUTCONFIGURATION model class and thn i tried to change the the combobox value which comes from LoadFile method, hence it comes as class cast exception. kindly help me how to solve this class cast exception error.

Fixing setCellFactory in javafx

I have problem with to set a setCellFactory column.
My code looks like this:
#FXML
private void EditStudentMarkAction(Integer idUser){
ObjectMapper mapper = new ObjectMapper();
List<Marks> lista = null;
String path = "http://localhost:8080/Server/source/users/"+idUser+"/marks";
try {
lista = mapper.readValue(new URL(path), new TypeReference<List<Marks>>(){});
} catch (IOException ex) {
System.out.println(ex);
}
ObservableList<Marks> lis = FXCollections.observableArrayList(lista);
columnFirst.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getTest().getTitle()));
columnSecond.setCellValueFactory(new PropertyValueFactory<Marks,String>("date"));
columnThird.setEditable(true);
columnThird.setCellValueFactory(new PropertyValueFactory<Marks,String>("mark"));
columnThird.setCellFactory(TextFieldTableCell.forTableColumn());
columnThird.setOnEditCommit(
new EventHandler<CellEditEvent<Marks, String>>() {
#Override
public void handle(CellEditEvent<Marks, String> t) {
((Marks) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setMark(Float.parseFloat(t.getNewValue()));
}
}
);
tableEdit.getColumns().setAll(columnFirst,columnSecond,columnThird);
tableEdit.setItems(lis);
}
Error:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.String
When I comments line:
columnThird.setCellFactory(TextFieldTableCell.forTableColumn());
That's my code works, but I can't to edit a row.
So I must translate Float to String in method setCellFactory something like this Stack yes? but I must change Integer to Float?
I added the following code, but still no work and do not build program:
columnThird.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<Float>() {
#Override
public String toString(Float t) {
return t.toString();
}
#Override
public Float fromString(String string) {
return Float.parseFloat(string);
}
}));

PropertyEditorSupport method not executed

i want use spring mvc convert json to one object like
#RequestMapping(value = "searchPolygonArea/", method = RequestMethod.GET,params = {"region != null"})
public #ResponseBody ResultBean <List <Spot>> searchPolygonArea(#ModelAttribute (value="regionModel") Region regions,#RequestParam(value="region") Region region){
return new ResultBean <List<Spot>> ();
}
#InitBinder(value="regionModel")
public void initBinder(WebDataBinder dataBinder,#RequestParam(value="region") final String regionParams){//,
dataBinder.registerCustomEditor (Region.class, new PropertyEditorSupport (){
Region value ;
#Override
public Object getValue () {
return new Region ();
}
#Override
public void setAsText (String text) throws IllegalArgumentException {
System.out.println (text);
try {
value = JSONUtils.json2Obj (text, Region.class);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
but setAsText and getValue not executed , i don't know why.

Resources