How to recursively get all fields in a unidirectional relationship? - relationship

I am trying to write a recursive method in java for getting all the fields in a unidirectional relationship. For example, I have one class A and it has number of fields and one of the field has a unidirectional relationship with class B. So I want the names of the fields of class A as well as of class B.
I am trying the below code but no success:
public class testReflection {
public static void main(String[] args) {
try {
C c = new C();
Class klass = c.getClass();
Field[] fields = getAllFields(klass);
for (Field field : fields) {
System.out.println(field.getName());
}
} catch (Throwable a_th) {
a_th.printStackTrace();
}
}
public static Field[] getAllFields(Class klass) {
List<Field> fields = new ArrayList<Field>();
fields.addAll(Arrays.asList(klass.getDeclaredFields()));
if (klass.getSuperclass() != null) {
fields.addAll(Arrays.asList(getAllFields(klass.getSuperclass())));
}
return fields.toArray(new Field[] {});
}
}
How do I achieve this? Thanks!

Related

JavaFX 8 How to pass and use a reference to a method that doesn't return a value?

I'm trying to pass and use a method reference to another method. The reference is to a setter in a TableView's model class that accepts a String input parameter and doesn't return a value.
In my FMXL controller, I'm dynamically creating table columns that contain Combo Boxes. The code is based on James_D's solution here: Java FX ComboBoxTableCell Show In Every Cell. I pass the method reference as follows:
TableColumn<TestModel, DBComboChoice> colComboBoxField = DAOGenUtil.createComboBoxColumn
("ComboBox Field",
TestModel::comboBoxFieldProperty, //this one works
TestModel::setComboBoxField, //this one doesn't work
comboData);
I'm stuck in two places in the createComboBoxColumn method - in the method declaration and in the setOnAction.
public <S> TableColumn<S, DBComboChoice> createComboBoxColumn(String title,
Function<S, StringProperty> methodGetComboFieldProperty,
//==> <WHAT-GOES-HERE?> methodSetComboField,
ObservableList<DBComboChoice> comboData ) {
TableColumn<S, DBComboChoice> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> {
String masterCode = methodGetComboFieldProperty.apply(cellData.getValue()).get();
DBComboChoice choice = DBComboChoice.getDescriptionByMasterCode(masterCode, comboData);
return new SimpleObjectProperty<>(choice);
});
col.setCellFactory((TableColumn<S, DBComboChoice> tablecol) -> {
ComboBox<DBComboChoice> combo = new ComboBox<>();
combo.getItems().addAll(comboData);
TableCell<S, DBComboChoice> cell = new TableCell<S, DBComboChoice>() {
#Override
protected void updateItem(DBComboChoice choice, boolean empty) {
super.updateItem(choice, empty);
if (empty) {
setGraphic(null);
} else {
combo.setValue(choice);
setGraphic(combo);
}
}
};
combo.setOnAction((ActionEvent event) -> {
String masterCode = combo.getSelectionModel().getSelectedItem().getMasterCode();
//==> col.getTableView().getItems().get(cell.getIndex()).<AND-HOW-DO-I-USE-IT-TO-SET-THE-DATA-MODEL'S-FIELD-TO-masterCode?>
});
return cell ;
});
return col;
}
When I tried Function<S, Void> methodSetComboField, I got an error in the FXML controller ("method createComboBoxColumn in class DAOGenUtil cannot be applied to given types"). BiConsumer<S, String> methodSetComboField didn't generate an error but I couldn't figure out how to use it in the setOnAction.
Can anyone help please? I'm using JavaFX8, NetBeans 8.2 and Scene Builder 8.3.
DBComboChoice is a class that contains a masterCode and a masterDescription eg. "F" for "Female", "M" for "Male". The masterCode is stored in the TableView's model. The masterDescription is shown in the ComboBox. I'm loading the values from a database master table.
Here are the relevant bits from the TableView's data model class:
public class TestModel {
//...
public String getComboBoxField() {
return comboBoxField.get();
}
public void setComboBoxField(String comboBoxField) {
this.comboBoxField.set(comboBoxField);
}
public StringProperty comboBoxFieldProperty() {
return comboBoxField;
}
//...
}
Let's take a look at the signature available:
void setComboBoxField(String)
since you don't want to specify the instance but use TestModel::setComboBoxField, you need a functional interface with a method that accepts 2 parameters: TestModel and String. You could create such an interface yourself easily
#FunctionalInterface
public interface MyInterface<S, T> {
void call(S s, T t);
}
public <S> TableColumn<S, DBComboChoice> createComboBoxColumn(String title,
Function<S, StringProperty> methodGetComboFieldProperty,
MyInterface<? super S, ? super String> methodSetComboField,
ObservableList<DBComboChoice> comboData )
Or use the existing interface BiConsumer:
public <S> TableColumn<S, DBComboChoice> createComboBoxColumn(String title,
Function<S, StringProperty> methodGetComboFieldProperty,
BiConsumer<? super S, ? super String> methodSetComboField,
ObservableList<DBComboChoice> comboData ) {
...
methodSetComboField.accept(col.getTableView().getItems().get(cell.getIndex()), masterCode);
...
}

Exception when trying to use DynamoDBMapper: no mapping for HASH key

I have a DynamoDB table with a primary key (id : integer) and secondary key (dateTo : String). I've made a Class that utilizes DynamoDBMapper:
#DynamoDBTable(tableName="MyItems"
public class MyItemsMapper {
private int id;
private String dateTo;
private String name;
#DynamoDBHashKey(attributeName="id")
public void setId(int id) { this.id = id; }
public int getId() { return id; }
#DynamoDBAttribute(attributeName="dateTo")
public void setDateTo(String dateTo) { this.dateTo = dateTo; }
public String getDateTo() { return dateTo; }
#DynamoDBAttribute(attributeName="name")
public void setName(String name { this.name = name; }
public String getName() { return name; }
public boolean saveItem(MyItemsMapper item) {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client); //<-- This connects to the DB. This works fine.
item.setId(generateUniqueNumber()); //<-- This generates a unique integer. Also seems to work fine.
mapper.save(item);
logger.info("Successfully saved item. See info below.");
logger.info(item.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
}
I then have a manager class that uses the bean above, like so:
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem(myItemsMapper);
}
}
I am running the manager class in a JUnit test:
public class MyManagerTest {
#Test
public void saveNewItemTest() {
MyManager myManager = new MyManager();
myManager.recordItem(1234567, "2018-01-01", "Anthony");
}
}
When I use the saveItem method above via my manager by running my JUnit test, I get the following error:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: MyItemsMapper; no mapping for HASH key
Not really sure what it's pertaining to, as I definitely have a primary key for my table and my secondary key always has a value as well.
How do I get this to work?
More Info:
It's worth noting that I can record data into my DynamoDB table via the Item object. If I do the below, my data gets recorded into the database:
DynamoDB dynamoDB = new DynamoDBClient().connectToDynamoDB(); //<--
Connection. Works fine.
Table table = dynamoDB.getTable("MyItems");
item.withPrimaryKey("id", 1234567);
item.withString("dateTo", "2018-01-01");
item.withString("name", "Anthony");
PutItemOutcome outcome = table.putItem(item);
However, I'm trying to use DynamoDBMapper because I'm reading that it is a more organized, better way to access data.
Im not sure if this is causing the problem, but you are creating the myItemsMapper object, then passing a reference to this object to itself.
I would suggest removing your saveItem method. The MyItemsMapper class should be a plain old java object. Then make MyManager like this
public class MyManager {
public boolean recordItem(
int id,
String dateTo,
String name,
) {
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(myItemsMapper);
}
}
If you particularly want to keep the saveItem method make it like this
public boolean saveItem() {
try {
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(this);
logger.info("Successfully saved item. See info below.");
logger.info(this.toString());
return true;
} catch (Exception e) {
logger.error("Exception while trying to save item: " + e.getMessage());
e.printStackTrace();
return false;
}
}
And then in MyManager do
MyItemsMapper myItemsMapper = new MyItemsMapper();
myItemsMapper.setId(id);
myItemsMapper.setDateTo(dateTo);
myItemsMapper.setName(name);
myItemsMapper.saveItem();

Spring AOP - Database Auditing

I'm using Spring AOP trying to define a good approach to have all my tables audited with no much hassle. Example of scenario:
I have a table named Person and its respective table PersonLog, which will store the Person values in addition to the user who modified, when and the type of the event, for each update.
Simply put, my question is:
I'm trying to come up with a way that my advice class would be smart enough to handle any new table being audited without any needed modification to it... let's say that I created the table Car and its CarLog table, if I could avoid the need to change anything in my advice implementation (it would automatically identify Car as being audited and would be able to persist a CarLog entity) ---> I can identify table Car as being audited pretty easily (by annotation), but I'm struggling to find a way to create and persist a CarLog instance dynamically.
Can anyone think of a way to accomplish that? Thanks.
This is called "change data capture" or CDC.
Personally, I don't think this is a good use for Spring or AOP. I think it would be better done in the database itself, especially if the database is shared/modified by more than one application.
You don't say which database you're using, but I'd recommend digging into your vendor's docs to find out what they have out of the box to support CDC.
i had similiar requirement in project where i am suppose to take snapshot of complex object graph before saving.
solution i have applied is 1) developed custom annotation #Archivable with certain attribute like nullify,ignore, orignal, setArchiveFlag
2) written hiberante deep cloner utility which create replica of object and insert into same table. deep cloner works on simple trick searlize and then desearlize object this will create new instances and then set id and version to null.
3) used cloner utility in entity interceptor to take decision weather to archive or not.
below is some of that code.
#Retention(RetentionPolicy.RUNTIME)
#Target( { ElementType.TYPE })
public #interface Archivable {
/** This will mark property as null in clone */
public String[] nullify() default {};
/**
* If property is archivable but not from enclosing entity then specify as
* ignore.
*/
public String[] ignore() default {};
/**
* sets original reference to clone for back refer data. This annotation is
* applicable to only root entity from where archiving started.
*
* #return
*/
public String original() default "";
/**
* if marks cloned entity to archived, assumes flag to be "isArchived".
* #return
*/
public boolean setArchiveFlag() default false;
}
#Component
public class ClonerUtils {
private static final String IS_ARCHIVED = "isArchived";
#Autowired
private SessionFactory sessionFactory;
public Object copyAndSave(Serializable obj) throws Exception {
List<BaseEntity> entities = new ArrayList<BaseEntity>();
Object clone=this.copy(obj,entities);
this.save(clone, entities);
return clone;
}
public Object copy(Serializable obj,List<BaseEntity> entities) throws Exception{
recursiveInitliaze(obj);
Object clone = SerializationHelper.clone(obj);
prepareHibernateObject(clone, entities);
if(!getOriginal(obj).equals("")){
PropertyUtils.setSimpleProperty(clone, getOriginal(obj), obj);
}
return clone;
}
private void save(Object obj,List<BaseEntity> entities){
for (BaseEntity baseEntity : entities) {
sessionFactory.getCurrentSession().save(baseEntity);
}
}
#SuppressWarnings("unchecked")
public void recursiveInitliaze(Object obj) throws Exception {
if (!isArchivable(obj)) {
return;
}
if(!Hibernate.isInitialized(obj))
Hibernate.initialize(obj);
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
for (PropertyDescriptor propertyDescriptor : properties) {
Object origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
if (origProp != null && isArchivable(origProp) && !isIgnore(propertyDescriptor, obj)) {
this.recursiveInitliaze(origProp);
}
if (origProp instanceof Collection && origProp != null) {
for (Object item : (Collection) origProp) {
this.recursiveInitliaze(item);
}
}
}
}
#SuppressWarnings("unchecked")
private void prepareHibernateObject(Object obj, List entities) throws Exception {
if (!isArchivable(obj)) {
return;
}
if (obj instanceof BaseEntity) {
((BaseEntity) obj).setId(null);
((BaseEntity) obj).setVersion(null);
if(hasArchiveFlag(obj)){
PropertyUtils.setSimpleProperty(obj, IS_ARCHIVED, true);
}
entities.add(obj);
}
String[] nullifyList = getNullifyList(obj);
for (String prop : nullifyList) {
PropertyUtils.setProperty(obj, prop, null);
}
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
for (PropertyDescriptor propertyDescriptor : properties) {
if (isIgnore(propertyDescriptor, obj)) {
continue;
}
Object origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
if (origProp != null && isArchivable(origProp)) {
this.prepareHibernateObject(origProp, entities);
}
/** This code is for element collection */
if(origProp instanceof PersistentBag){
Collection elemColl=createNewCollection(origProp);
PersistentBag pColl=(PersistentBag) origProp;
elemColl.addAll(pColl.subList(0, pColl.size()));
PropertyUtils.setSimpleProperty(obj, propertyDescriptor.getName(), elemColl);
continue;
}
if (origProp instanceof Collection && origProp != null) {
Collection newCollection = createNewCollection(origProp);
PropertyUtils.setSimpleProperty(obj, propertyDescriptor.getName(), newCollection);
for (Object item : (Collection) origProp) {
this.prepareHibernateObject(item, entities);
}
}
}
}
#SuppressWarnings("unchecked")
private Collection createNewCollection(Object origProp) {
try {
if(List.class.isAssignableFrom(origProp.getClass()))
return new ArrayList((Collection)origProp);
else if(Set.class.isAssignableFrom(origProp.getClass()))
return new HashSet((Collection)origProp);
else{
Collection tempColl=(Collection) BeanUtils.cloneBean(origProp);
tempColl.clear();
return tempColl;
}
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList();
}
private boolean isIgnore(PropertyDescriptor propertyDescriptor,Object obj){
String propertyName=propertyDescriptor.getName();
String[] ignores=getIgnoreValue(obj);
return ArrayUtils.contains(ignores, propertyName);
}
private String[] getIgnoreValue(Object obj) {
String[] ignore=obj.getClass().getAnnotation(Archivable.class).ignore();
return ignore==null?new String[]{}:ignore;
}
private String[] getNullifyList(Object obj) {
String[] nullify=obj.getClass().getAnnotation(Archivable.class).nullify();
return nullify==null?new String[]{}:nullify;
}
public boolean isArchivable(Object obj) {
return obj.getClass().isAnnotationPresent(Archivable.class);
}
private String getOriginal(Object obj) {
String original=obj.getClass().getAnnotation(Archivable.class).original();
return original==null?"":original;
}
private boolean hasArchiveFlag(Object obj) {
return obj.getClass().getAnnotation(Archivable.class).setArchiveFlag();
}
#SuppressWarnings({ "unchecked", "unused" })
private Collection getElemColl(Object obj, Object origProp) {
Collection elemColl=createNewCollection(origProp);
for (Object object : (Collection)origProp) {
elemColl.add(object);
}
return elemColl;
}
#SuppressWarnings("unused")
private boolean isElementCollection(Object obj, String name) {
try {
Annotation[] annotations=obj.getClass().getDeclaredField(name).getAnnotations();
for (Annotation annotation : annotations) {
if(annotation.annotationType() == ElementCollection.class)
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Envers is what you require for auditing purposes

Passing a list or array to RESTeasy using get

I've seen this kind of thing described in various examples showing how to create a REST service which takes arrays or a list of objects as part of the URL.
My question is, how to implement this using RESTeasy?
Something like the following would be how i would assume this to work.
#GET
#Path("/stuff/")
#Produces("application/json")
public StuffResponse getStuffByThings(
#QueryParam("things") List<Thing> things);
Create a StringConverter and a use a wrapper object. Here is a quick and dirty example:
public class QueryParamAsListTest {
public static class Thing {
String value;
Thing(String value){ this.value = value; }
}
public static class ManyThings {
List<Thing> things = new ArrayList<Thing>();
ManyThings(String values){
for(String value : values.split(",")){
things.add(new Thing(value));
}
}
}
static class Converter implements StringConverter<ManyThings> {
public ManyThings fromString(String str) {
return new ManyThings(str);
}
public String toString(ManyThings value) {
//TODO: implement
return value.toString();
}
}
#Path("/")
public static class Service {
#GET
#Path("/stuff/")
public int getStuffByThings(
#QueryParam("things") ManyThings things){
return things.things.size();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addStringConverter(new Converter());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/stuff?things=a,b,c");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals("3", response.getContentAsString());
}
}
I think you can also use a StringParamUnmarshaller
I had some luck with this, using Collection rather than List. I was unable to make a StringConverter for List work.
#Provider
public class CollectionConverter implements StringConverter<Collection<String>> {
public Collection<String> fromString(String string) {
if (string == null) {
return Collections.emptyList();
}
return Arrays.asList(string.split(","));
}
public String toString(Collection<String> values) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (String value : values) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(value);
}
return sb.toString();
}
}
I did the toString from my head. Be sure to write unit tests for it to verify. But of course, everything is easier and clearer when you use Guava. Can use Joiner and Splitter. Really handy.
Just use a wrapper on its own, no need for anything else.
In your endpoint
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/find")
#GET
MyResponse find(#QueryParam("ids") Wrapper ids);
And you wrapper looks like this :
public class Wrapper implements Serializable {
private List<BigInteger> ids = Collections.emptyList();
public String toString() {
return Joiner.on(",")
.join(ids);
}
public List<BigInteger> get() {
return ids;
}
public Wrapper(String s) {
if (s == null) {
ids = Collections.emptyList();
}
Iterable<String> splitted = Splitter.on(',')
.split(s);
Iterable<BigInteger> ids = Iterables.transform(splitted, Functionz.stringToBigInteger);
this.ids = Lists.newArrayList(ids);
}
public Wrapper(List<BigInteger> ids) {
this.ids = ids;
}
}

Store custom class instance in IsolatedStorage in Silverlight

I need to store different objects in IsolatedStorage and i'm using IsolatedStorageSettings class to do that. Some of that objects are base types so stored and retrieved well. But some of them are custom classes instances and they stored well, but when i try to retrieve them i get instances with the initial values.
How can i store custom classes instances in IsolatedStorage and retrieve them?
Phil Sandler, i guess so. but i don't know what type of serialization use isolated storage, so i don't know how to make my class serializable. Private fields also must be stored.
Here is the code of custom class:
public class ExtentHistory : INotifyPropertyChanged
{
private const int Capacity = 20;
private List<Envelope> _extents;
private int _currentPosition;
public event PropertyChangedEventHandler PropertyChanged;
public int ItemsCount
{
get { return _extents.Count; }
}
public bool CanStepBack
{
get { return _currentPosition > 0; }
}
public bool CanStepForward
{
get { return _currentPosition < _extents.Count - 1; }
}
public Envelope CurrentExtent
{
get { return (_extents.Count > 0) ? _extents[_currentPosition] : null; }
}
public ExtentHistory()
{
_extents = new List<Envelope>();
_currentPosition = -1;
}
public void Add(Envelope extent)
{
if (_extents.Count > Capacity)
{
_extents.RemoveAt(0);
_currentPosition--;
}
_currentPosition++;
while (_extents.Count > _currentPosition)
{
_extents.RemoveAt(_currentPosition);
}
_extents.Add(extent);
}
public void StepBack()
{
if (CanStepBack)
{
_currentPosition--;
NotifyPropertyChanged("CurrentExtent");
}
}
public void StepForward()
{
if (CanStepForward)
{
_currentPosition++;
NotifyPropertyChanged("CurrentExtent");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And here are the functions of storing and retrieving:
private IsolatedStorageSettings _storage;
public void Store(string key, object value)
{
if (!_storage.Contains(key))
{
_storage.Add(key, value);
}
else
{
_storage[key] = value;
}
}
public object Retrieve(string key)
{
return _storage.Contains(key) ? _storage[key] : null;
}
I don't want to serialize manually every object to add, i want to make custom class serializable by default to store it in isolated storage (if it's possible)
My inital guess would be a serialization problem. Do all your properties have public setters? Post the classes you are storing and the code you are using to store them.
I believe IsolatedStorageSettings uses the DataContractSerializer by default. If you want ExtentHistory to be serialized, you should read up on what you need to do to get it to work properly with this serializer:
DataContractSerializer Class
You might create a separate object strictly for the purpose of storing the data in Isolated storage (sort of like a DTO). This will allow you to keep ExtentHistory as-is.

Resources