vendredi 28 juillet 2017

Jackson Pojo to correct Implementation

I am in a situation where I can't wrap my head around the solution. The Problem is that I can't use CDI.

Let me show you my sorrounding. I am developing a java console application to later on perform long time tests and simulations. These are needed to find bugs and behaviour of our real application for some tasks and scenarios running over weeks etc.

I have this POJO structure:

POJO structure

And I am using Jackson to import settings for the various number of implementations I receive. The JSON looks like this for my POJO Wrapper:

{
    "devices": [
    {
    "host": "asd",
    "port": 136,
    "protocol": "rollenschneider"
    }, 
    {
    "host": "asd",
    "port": 136,
    "protocol": "fg"
    } <-- These are the TcpDevice POJOs
    ]
}

Now I have the Wrapper POJO available and need to change this wrapper pojo to the actual Object I need which is defined in the JSON itself.

Here is an example code:

ObjectMapper mapper = new ObjectMapper();
JsonFactory f = mapper.getFactory();
File jsonFile = new File( filePath );

try ( JsonParser p = f.createParser( jsonFile ) )
{
  try ( MappingIterator<TcpDeviceWrapperImpl> deviceWrappers = mapper.readValues( p, TcpDeviceWrapperImpl.class ) )
  {
    while ( deviceWrappers.hasNext() )
    {
      TcpDeviceWrapper devicewrapper = deviceWrappers.next();
      List<TcpDeviceImpl> devices = devicewrapper.getDevices();
      for ( TcpDevice device : devices )
      {
        String protocol = device.getProtocol();
        switch ( protocol )
        {
          case TcpProtocols.BERST:
            break;
          case TcpProtocols.CMT:
            break;
          case TcpProtocols.FG:
            break;
          case TcpProtocols.SCT:
            break;
          case TcpProtocols.HÜLSENSÄGE:
            break;
          case TcpProtocols.ROLLENSCHNEIDER:
            RollCutterDevice rollCutter = (RollCutterDevice) devicewrapper;
            cxManager.addDevice( rollCutter.getName(), rollCutter );
            break;
          default:
            break;
        }
      }
    }
  }
}

Naturally the cast I performed in the switch-case is not working.

I know that I could research Reflection to perform the task I need ( not sure if that would work though ), but I also know that this way of doing things is not good. I would like to avoid using reflection.

Now I am asking how I can cast the POJO for TcpDevice to the actual Implementation I need. The fields are all the same with the only exception that the other protocols have additional functions.





Aucun commentaire:

Enregistrer un commentaire