How to map one object to the other object in java - java

I am implementing a component where one component receive a message, it sends another message to Audit component so it can be audited.
Audit handler has model called AuditObject, and my component has MessageObject. Here is the code:
public final class AuditObject {
private final Long id;
private final String studyUid;
private final AuditPatient patient;
...
}
public final class MessageObject {
private final Long id;
private final String studyUid;
private final PatientObject patient;
private final String accessorName;
...
}
AuditPatient and PatientObject have same variables.
I am trying to send it through amqp connection via jms message. I already have MessageGateway. So my code will look like this on my side.
public void send(MessageObject messageObject) {
//translate MessageObject to AuditObject
messageGateway.send(auditObject, endpoint);
}
What is the best way to translate(or map) MessageObject to AuditObject? Do I have to manually create each fields by assigning them? What is the best way to approach this problem?

Use static method in a class to convert one object to another and call it.
class ConvertObject {
public static AuditObject convertMessageObjectToAudioObject(MessageObject messageObject) {
AuditObject auditObject = new AuditObject();
auditObject.setStudyUid(messageObject.getStudyUid());
auditObject.setPatient(messageObject.getPatient());
return auditObject;
}
}
public void send(MessageObject messageObject) {
AuditObject auditObject = ConvertObject.convertMessageObjectToAudioObject(messageObject);
messageGateway.send(auditObject, endpoint);
}

Related

ORMLite does not know how to store interface java.util.List

Product
#DatabaseTable
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
public Product() {
// TODO Auto-generated constructor stub
}
public Product(String originalId) {
this.originalId = originalId;
}
#DatabaseField(id = true)
private String originalId;
...
#DatabaseField
private List<SkuInfo> skusInfo;
SkuInfo
public class SkuInfo implements Serializable {
private static final long serialVersionUID = 1L;
...
}
The error is:
java.lang.IllegalArgumentException: ORMLite does not know how to store interface java.util.List for field skusInfo. Use another class or a custom persister.
When I used:
#DatabaseField(dataType = DataType.SERIALIZABLE)
private List<SkuInfo> skusInfo;
The error change to:
java.lang.IllegalArgumentException: ORMLite does not know how to store interface java.util.List for field skusInfo. Use another class or a custom persister.
I already read in another posts about the tag Foreign but my item is not a foreign key.
I used a Custom Serializable Object like posted here and worked.
public class SerializableCollectionsType extends SerializableType {
private static SerializableCollectionsType singleton;
public SerializableCollectionsType() {
super(SqlType.SERIALIZABLE, new Class<?>[0]);
}
public static SerializableCollectionsType getSingleton() {
if (singleton == null) {
singleton = new SerializableCollectionsType();
}
return singleton;
}
#Override
public boolean isValidForField(Field field) {
return Collection.class.isAssignableFrom(field.getType());
}
}
Product
#DatabaseField(persisterClass = SerializableCollectionsType.class)
private List<SkuInfo> skusInfo;
java.lang.IllegalArgumentException: ORMLite does not know how to store interface java.util.List for field skusInfo. Use another class or a custom persister.
Just for posterity, you could have changed this to be an ArrayList which actually implements java.io.Serializable since that's what it is looking for. Unfortunately the List doesn't so ORMLite throws the exception.

How to avoid making long constructors [duplicate]

This question already has answers here:
Elegant alternatives for huge amount of arguments in class constructor [closed]
(4 answers)
Closed 7 years ago.
I have a client library in which I am making http remote calls to my rest service and then I am returning List<DataResponse> back to the customer who is calling our library with the response I am getting from my REST service along with any errors if there are any wrapped around DataResponse object.
public class DataResponse {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
// constructors and getters here
}
Here is my ErrorCode enum class:
public enum ErrorCode {
// enum values
private final int code;
private final String status;
private final String description;
// constructors and getters
}
And here is my StatusCode enum class:
public enum StatusCode {
SUCCESS, FAILURE;
}
As you can see in my DataResponse class I have lot of fields so basis on that I have a very long constructor and everytime when I make a DataResponse object I have a big line with new DataResponse(.......). In future I might have more fields but for now I only have these fields.
Is there any better way I can use to make a DataResponse object and then return back List<DataResponse> from my library?
Do not use the builder pattern right away. It is not for types with tons of required fields. It's for types with tons of optional fields.
Builders' required properties are specified via the constructor. You are not forced to define values using methods, which makes those values optional.
This leaves potential for your object being only partially constructed. Using a builder for this would be abuse of the design.
With that said, you should decompose your type. I'm not sure what lmd or ctime is, or really what a DataResponse is supposed to represent, so I cannot tell you in which way you should decompose. But I can tell you cohesion is what determines such.
isLink, maskInfo and idType could possibly be decomposed into a DataResponseDetails object:
class DataResponseDetails {
private boolean isLink;
private String maskInfo;
private TypeOfId idType;
public DataResponseDetails(boolean isLink, String maskInfo, TypeOfId idType) {
//...
}
}
Now your DataResponse could be composed of DataResponseDetails:
class DataResponse {
private DataResponseDetails details;
private String response;
//...
public DataResponse(DataResponseDetails details, String response, ...) {
//...
}
}
Feel your constructor requires too much still? Decompose more!
Maybe you can identify smaller logical groups of fields an move them into objects of an own class. Then you can assemble all these objects in your DataResponse objects.
As Joshua Bloch stated it in Item 2 of Effective Java 2nd Edition, you should consider using a builder pattern, as it is a best practice.
Here is what you code could look like using it :
public class DataResponse {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
// constructors and getters here
public static class Builder {
private final String response;
private final boolean isLink;
private final TypeOfId idType;
private final long ctime;
private final long lmd;
private final String maskInfo;
// below are for error stuff
private final ErrorCode error;
private final StatusCode status;
public Builder reponse(final String response) {
this.response = response;
return this;
}
public Builder isLing(final boolean isLink) {
this.isLink = isLink;
return this;
}
public DataResponse builder() {
return new DataResponse(this);
}
...
}
private DataResponse(final Builder builder) {
this.response = builder.response;
this.isLink = builder.isLink;
}
}
and then do something as follow :
DataResponse response = new DataResponse.Builder().reponse(anyResponse).isLink(isLink).build();

Map selected fields from multiple POJOs to create one POJO

I have a couple of objects from which selected members should be combined to create an output object. All these are POJOs. I am seeing that all object mappers work on a single POJO to another POJO level. Is there any mapper that supports what I am looking for? Of course, I understand that there is some mapping stuff that I need to specify.
Edit:
I know how to get this done by writings own Java class. I am just looking for a way to do it with one of the mapping libraries.
You aren't limited in what you require to be passed to your mapper. You can define it to accept several items and build the object based on the multiple inputs. Here is an example:
public class ClassOne {
private final String someProperty;
public ClassOne(String someProperty) {
this.someProperty = someProperty;
}
public String getSomeProperty() {
return someProperty;
}
}
public class ClassTwo {
private final String someOtherProperty;
public ClassTwo(String someOtherProperty) {
this.someOtherProperty = someOtherProperty;
}
public String getSomeOtherProperty() {
return someOtherProperty;
}
}
public class CombinedClass {
public static CombinedClass mapper(ClassOne one, ClassTwo two){
return new CombinedClass(one.getSomeProperty(), two.getSomeOtherProperty());
}
private final String someProperty;
private final String someOtherProperty;
private CombinedClass(String someProperty, String someOtherProperty) {
this.someProperty = someProperty;
this.someOtherProperty = someOtherProperty;
}
public String getSomeProperty() {
return someProperty;
}
public String getSomeOtherProperty() {
return someOtherProperty;
}
}

create database connection once only

public class Database {
private String ric;
private String volume;
private String _url;
private String _userId;
private String _password;
private String _dbLib;
private String _dbFile;
private Connection _conn;
private PreparedStatement _statement;
public Database(LSE item) {
ric = item.get_ric();
volume = item.get_volume();
}
public void writeToDb() throws SQLException{
//setString
}
}
I have a ItemDispatcher class:
public class ItemDispatcher implements Runnable {
private LSE lse;
public ItemDispatcher(LSE lseItem) {
this.lse= lseItem;
}
#Override
public void run() {
try {
new Database(lse).writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
run() method in ItemDispatcher runs repeatedly. I want to create database connection and prepareStatement in Database class, but doing this on Database class constuctor would create connection many times over. How can I change my design to create connection just once and not over and over again on every execution of run(). I am trying to not do this in any other class and just Database class
Within the scope of ItemDispatcher, declare private variable X of type Database. You might initialize it in a separate method (best) or in the constructor (might be ok). Use the private variable X instead of creating a new instance in method run
Do it in a static block in class Database
static {
}
But this implies that Connections and Statement will be static and then shared by all instances of Database.
Just as an example from another SO post:
public static final Map<String, String> initials = new HashMap<String, String>();
static {
initials.put("AEN", "Alfred E. Newman");
// etc.
}
Use the Singleton pattern . This will allow you to have only one instace of the Database connection.
Taking your code as an example, it would be like this :
public class Database {
private String ric;
private String volume;
private String _url;
private String _userId;
private String _password;
private String _dbLib;
private String _dbFile;
private Connection _conn;
private PreparedStatement _statement;
private static final Database INSTANCE;
private Database(LSE item) {
ric = item.get_ric();
volume = item.get_volume();
}
public static final Database getInstance(LSE item) {
if (INSTANCE == null) {
INSTANCE = new Database(LSE item);
}
return INSTANCE;
}
public void writeToDb() throws SQLException{
//setString
}
}
If your application will be using Threads (Concurrency), I suggest you also to prepare your singleton for those situations , see this question

Inline instanced class as parameter in an Enum

I'm new in java programming and trying to learn it.
I ran into a problem that cannot find a solution for it in the web:
I have an enum, that is a "list" of actions and each of them has a property
of type Actions that conains a list of possible subactions. The subacions are constant string.
I'd like to instanziate a anonymus instance of Actions in the enum constructor so that
in addition to the standart subactions, each enum could have its subactions
I tried to write an enum like the following
public enum Action {
ACTION1("One", new Actions(){
public static final String TEST = "test";
}),
ACTION2("TWO", null),
ACTION3("THREE,null);
private final String act;
public final Actions actions;
private Action(String act, Actions actions) {
this.act = act;
this.actions = actions;
}
}
and this is Actions class
public class Actions {
public static final String SUBACTION_TEST1 = "suoOne";
public static final String SUBACTION_TEST2 = "subTwo";
}
than, this is how I use the Action enum:
String as = Action.ACTION1.params.SUBACTION_TEST1;
and up to here it wors but I'cannot write this:
String ast = Action.ACTION1.params.TEST;
I know that probably this approach is wrong but before the change the implementation
I'd like to know why doesn't work.
Thanks.
Your enum has no property named params, which is the immediate reason your code example does not work. One thing you could do to improve this design, is to have your Actions class return the list of sub-actions via a well defined method:
public class Actions {
public static final String SUBACTION_TEST1 = "suoOne";
public static final String SUBACTION_TEST2 = "subTwo";
public List<String> getSubActions() {
return Arrays.asList(SUBACTION_TEST1, SUBACTION_TEST2);
}
}
public enum Action {
ACTION1("One", new Actions(){
public static final String TEST = "test";
#Override
public List<String> getSubActions() {
return Arrays.asList(TEST);
}
}),
private final String act;
private final Actions actions;
private Action(String act, Actions actions) {
this.act = act;
this.actions = actions;
}
public Actions getActions() {
return actions;
}
}
And to use this:
List<String> subActionList = Action.ACTION1.getSubActions();

Categories

Resources