Simple Java field injection with Micronaut what's the missing step(s)? - java

I am not sure yet if I'm on the wrong track or not. There is an example on the Micronaut Getting Started page for a V8 Engine and injecting a Vehicle.
Defining Beans (often used Engine interface example)
With that example in mind. What is the most straightforward way to implement "Model A" with Micronaut using Java? If there's no direct approach, what is the closest hands-off method with Micronaut?
My simple vision of vanilla field injection stepping-on with such an example is as so (using Java), I'm labelling it "Model A" ...
Model A
import io.micronaut.context.*
public class MyApp { // (A)
#Inject
Vehicle vehicle;
public void runApp( String... args ){
println( vehicle.start() )
}
public static main( String... args ){
// whatever set-up and steps need // (B)
// for auto-inject / auto-wiring.
MyApp body = new MyApp( args );
body.runApp(); // (C)
}
}
Where the annotation processor uses provides an instance of the #Singleton Vehicle in this example. Or creates a new instance in the case of non-singleton-s.
Either way the result of the process would be that I don't need to write code to 'instantiate' the code or find a factory to do so explicitly.
The example itself goes on to demonstrate the method I'll label "Model B" (using Groovy)...
Model B
import io.micronaut.context.*
...
Vehicle vehicle = BeanContext.run().getBean(Vehicle)
println( vehicle.start() )
Which in fact is MORE typing than just writing:
Vehicle vehicle = new Vehicle();
// OR
Vehicle vehicle = Vehicle.getInstance();
With some libraries you need to initialise the scopes or context, I see that. The question boils donw to what must I do to inject Vehicle as shown in my code.
I made a #Singleton and tried to #Inject the field. The reference is NULL. I then made a #Providerand set a break point. That isn't called.
can I do "Model A"?
If yes, what needs to happen?
I've scanned lots of examples doing great things. I'd love to get into those fancy things too. Right now I'm in the basement looking for a way up to the ground floor. Many thanks for you guidance.

Related

How to do train composition - compositon of classes

I am currently working on a train simulation project for uni.
This is my class hierarchy:
RollingStock
Coach
FreightCoach
PassengerCoach
SpecialCoach
Engine
DieselEngine
ElectricEngine
SteamEngine
Trainset
My questions:
Every coach has a unique ID. However, Engines and Trainsets share their ID-Space ("series-name"). "Name" is inherited by RollingStock and both Trainset and Engine have the attribute "series".
I've created a class "SharedIdSpace" to implement this feature. But I am not quite sure how to solve this nicely (TreeMap, ..., ?).
Now, my main problem is I have to implement the following feature:
"Rolling stock can be composed into a train. The following restrictions must be observed when composing:
There must always be at least one locomotive/train set at the beginning or end of a valid train.
When composing, it must always be considered whether the rolling stock has a suitable coupling at the desired composition point.
The rolling stock that is being composed has not yet been used in another train.
[...]"
How can I implement this? I'm afraid I have no useful idea.
Im not sure about what are you asking, but I will try to give you my aproximation:
You need to create a composite object where every object has an unique ID and need to pass some validations.
I would implement an "StoregeManager" a "ComposerManager" and add an abstract validator method in "RollingStock" that validate if the vagon can be added.
The flow would be something like this:
DISCLAIMER This is written in Java, but with notepad++, please dont check the sintaxis.
RollingStock freightCoach = StoregeManager.getFreightCoach();
RollingStock specialCoach = StoregeManager.getSpecialCoach();
RollingStock dieselEngine = StoregeManager.getDieselEngine();
// Check if they are null or throw an exception if has no more elements. Maybe from BBDD or from where you want
Composer.compone()
.add(dieselEngine)
.add(freightCoach)
.add(specialCoach)
.build()
And inside the componer, something like this:
public class Composer {
private StoregeManager storeManager; //Injected or initialized, as you want.
private static Train train;
public Composer build(){
train = new Train;
return this;
}
public Composer add(RollingStock rs) {
if(rs.isValid(train))
train.add(rs);
return this;
}
public RollingStock[] build() {
storageManager.ckeckTrain(train);
return train;
}
}
You can put the storage inside the Composer and pass as argument the classname of the vagon if you need another aproximation to your problem.
I hope this helps you.

Change persistence layer dynamically (upon runtime) with as few changes as possible

I am searching for a design pattern/way to exchange a (persistence) layer of my application dynamically (preferably even at runtime).
Why?
I'd like to be able to decide whether to save certain data to XML or a database on a "per instance"-basis. So I may decide that one project uses XML as a backend and another uses a database. I want to be flexible here and to be able to easily add another "driver" for e.g. Json or whatever.
Now assume the following setup:
We have a controller and we want to manage some data. We can choose between a SQL and XML implementation.
One possible (working) solution:
BasicController.scala
val myPersistenceLayer: PersistenceLayer = SQLPersistenceLayer
val apples: Seq[Apple] = myPersistenceLayer.getApples()
trait PersistenceLayer
{
def getApples(): Seq[Apple]
def getBananas(): Seq[Banana]
}
object SQLPersistenceLayer extends PersistenceLayer
{
override def getApples(): Seq[Apple] = {...}
override def getBananas(): Seq[Banana] = {...}
}
This is a rather nasty solution as one would have to add methods for each new Model (think fruit! ;)) not only in the trait, but also in every implementation. I like my single responsibility so I'd rather delegate that to the models instead, like:
trait PersistenceLayer
{
def getAll(model: Model): Seq[Model] = { model.getAll() }
}
trait Model
{
def getAll(): Seq[Model]
}
package "SQL"
class Apple extends Model
{
def getAll(): Seq[Apple] = { // do some SQL magic here }
}
package "XML"
class Apple extends Model
{
def getAll(): Seq[Apple] = { // do some XML magic here instead }
}
Now the big problem here is, even if I implement a concrete PersistenceLayer, like so:
object SQLPersistenceLayer extends PersistenceLayer {}
how could I tell the application to use the model of the right package?
If I use the SQLPersistenceLayer upon:
val apples = myPersistenceLayer.get(Apple)
I would need to import the right "Apple" class, which defeats the whole purpose because then I could just remove all other classes, import the right one and just use a generic "getAll()" method on it.
So again I would need to change the implementation at multiple lines, which is what I want to avoid.
I thought about something like giving a string with the package-name, like
val package = "sql" and in the controller to import it from the right package, but this is not really feasible and not really easy to accomplish and it's a rather nasty hack for something I'm obviously missing.
To make a long story short: I want to be able to switch the package to use for my persistence needs dynamically. In some dynamically typed languages I could come up with a solution, but not in Scala or any statically typed language, so I guess I'm not knowing a certain design pattern here
** Edit **
A thought occurred (ya, sometimes it happens ;)) and now I'm wondering whether something like this could lead to what I want:
namespace tld.app.persistence
trait PersistenceLayer
{
proteced val models: mutable.HashMap[String, Model] = new mutable.HashMap[String, Model]
def registerModel(key: String, model: Model): Unit =
{
models.remove(key)
models.put(key, model)
}
def get(model: String): Seq[Future[Model]] =
{
val m: Model = models.getOrElse(model, throw new Exception("No such model found!"))
m.get
}
}
trait Model
{
def get(): Seq[Future[Model]]
}
namespace tld.app.persistence.sql
object SQLPersistenceLayer extends PersistenceLayer
class Person extends Model
{
def get(): Seq[Future[Model]] =
{
// ... query the database
}
}
namespace tld.app.persistence.xml
object XMLPersistenceLayer extends PersistenceLayer
class Person extends Model
{
def get(): Seq[Future[Model]] =
{
// ... read in from the appropriate xml-file
}
}
object Settings
{
var persistenceLayer: PersistenceLayer = SQLPersistenceLayer // Default is SQLPersistenceLayer
}
Somewhere in the application:
Settings.persistenceLayer.get("person")
// Then a user-interaction happens
Settings.persistenceLayer = XMLPersistenceLayer
Settings.persistenceLayer.get("person")
The persistenceLayer normally stays the same, but the user can decide upon changing it. I'll have a deeper look at it, as soon as I can find time. But maybe somebody immediately spots a problem with that approach.
DI allows you to wire an implementation at compile time. There are many ways to do DI in Scala (Cake Pattern, Reader Monad, DI frameworks, etc).
If you want to wire the dependency on application startup then regular dependency mechanisms would work. You would just create an instance of desired dependency (SQL, XML) based on some condition and pass it to the code.
If you want to keep switching between dependencies during your application execution, i.e. sometimes you save to SQL, other times to XML then you can use something similar to Lift Injector, see also my answer here - option 2.
You can use runtime reflection to accomplish it. You need to specify and create class/object at runtime which you'll be passing to Persistency layer and then just call generic getAll method.
For details of reflection library -> http://docs.scala-lang.org/overviews/reflection/overview.html
It would be better to make companion object Apple which has getAll method implemented differently for each persistency layer.
Then access Apple objects with reflection by using full package name
val apple:sql.Apple = //Reflection library object access
val apple:xml.Apple = //Reflection library object access
val apples = myPersistenceLayer.get(apple)
I think you can achieve module-based inclusion with implicits + TypeTags with something along these lines
object SqlPersistence {
implicit def getAll[T: TypeTag](): Seq[T] = {/* type-based sql implementation*/}
}
object JsonPersistence {
implicit def getAll[T: TypeTag](): Seq[T] = {/* type-based json implementation*/}
}
object PersistenceLayer {
def getAll[T](implicit getter: Unit => Seq[T]): Seq[T] = getter
}
// somewhere else ...
import SqlPersistence._
PersistenceLayer.getAll[Apple]
The advantage is that you can decide on your persistence layer at the spot by bringing a corresponding import. The major downside is the same: you need to decide on your persistence layer with every call and make sure that it is what you think. Also, from my personal experience compiler is less helpful with tricky implicit corner cases, so there is a potential to spend more time debugging.
If you set your persistence layer once for an app, then DI would do fine, e.g. cake pattern. But then again, you either need to have a method per class or resort to reflection. Without reflection, it may look like that:
trait PersistenceLayer {
def getApples(): Apples
}
trait SqlPersistenceLayer extends PersistenceLayer {
override def getApples() = // sql to get apples
}
trait Controller {
this: PersistenceLayer =>
def doMyAppleStuff = getApples()
}
// somewhere in the main ...
val controller = new Controller with SqlPersistence {}
controller.doMyAppleStuff
Something similar is strategy pattern if that helps.
I think the repository pattern is your solution.
EDIT:
ok. thanks for "-1" thats ok because i did not explained my idea behind...
my example is only one of many others. so i hope that this is usefull for someone out there
i will try to explain my idea about using the repository and factory pattern.
for this i made a github repository with the example code: https://github.com/StefanHeimberg/stackoverflow-32319416
my setup ist nearly the same as in your question. but the difference is the following:
i did not use scala. but the concept would be the same...
my settings contains only a "flag" for the repository factory.
the "model" objects are persistence ignorance. that means the do not know how the are persisted. this is the concern of the repositories
i made dependency injection by hand cause this should be sufficient for the example
i have no "Controller" but i have "Application Services"...
the decition about the implementation used is made inside the factory on each call to the create() method.
the domain layer does not know anything about the used infrastructure implementation. the application layer is orchestrating the domain service and the infrastructure services (in my example only the repositories)
if you have any DI Container then the factory could by a Producer or soething else... depends on DI Container
package structure:
i have also made a simple integration test
public class AppleServiceIT {
private Settings settings;
private AppleService appleService;
#Before
public void injectDependencies() {
settings = new Settings();
final JdbcAppleRepository jdbcAppleRepository = new JdbcAppleRepository();
final JsonAppleRepository jsonAppleRepository = new JsonAppleRepository();
final AppleRepositoryFactory appleRepositoryFactory = new AppleRepositoryFactory(jdbcAppleRepository, jsonAppleRepository);
appleService = new AppleService(settings, appleRepositoryFactory);
}
#Test
public void test_findAppleById() {
// test with jdbc
settings.setRepositoryType(RepositoryTypeEnum.JDBC);
assertEquals("JDBC-135", appleService.findAppleById(135l).getMessage());
// test with json
settings.setRepositoryType(RepositoryTypeEnum.JSON);
assertEquals("JSON-243", appleService.findAppleById(243l).getMessage());
}
#Test
public void test_getApples() {
// test with jdbc
settings.setRepositoryType(RepositoryTypeEnum.JDBC);
assertEquals(2, appleService.getApples().size());
// test with json
settings.setRepositoryType(RepositoryTypeEnum.JSON);
assertEquals(3, appleService.getApples().size());
}
}

Best practice for grouping Java classes for instantiation clarity

I am building a piece of software that sends and receives messages in particular binary definitions and with a particular version. As such, I have classes that look like this, which vary mostly only in the package name (the version, in this case):
For version 1.5:
com.mydomain.clothesmessage.v0105.fielddefinitions.Field100
com.mydomain.clothesmessage.v0105.fielddefinitions.Field200
com.mydomain.clothesmessage.v0105.messagedefinitions.Pants
com.mydomain.clothesmessage.v0105.messagedefinitions.Socks
and for version 2.7:
com.mydomain.clothesmessage.v0207.fielddefinitions.Field100
com.mydomain.clothesmessage.v0207.fielddefinitions.Field200
com.mydomain.clothesmessage.v0207.messagedefinitions.Pants
com.mydomain.clothesmessage.v0207.messagedefinitions.Socks
The class that manages the transmission and reception of these messages uses all versions, depending on where the message comes from, etc.
My problem is that defining an instance of the class requires I use the entire package path, because otherwise it's ambiguous. Even if there exists a situation where I use only one version in a given file, a casual reader of the code won't be able to see what version is being used. Pants pants = new Pants() is ambiguous until you look at the imported package.
My ideal usage of this would be something like this:
V0207.Pants pantsMessage = new V0702.Pants();
That makes it very clear what version is being used. I could make this happen by creating the Pants message classes as inner classes of the V0207 class, but then the V0207 class becomes gigantic (there could be a hundred messages, each with 100 fields, for every given version). Is there possibly a way to #include an inner class, so they can be stored in separate files? This would be ideal.
I suppose I can emulate this with a wrapper class, that does something (silly?) like this, where there exists an instance of the Pants class in the V0207 object:
Object pantsMessage = V0207.pants.getClass().newInstance();
((com.mydomain.clothesmessage.v0207.messagedefinitions.Pants)pantsMessage).getZipperType();
But I dislike that. It looks contrived and requires try/catch and casting when in use. Terrible.
I could also use a factory. That would be a bit nicer, but requires a parent class (or interface) and would require casting when used, since each message has unique methods.
Message pantsMessage = V0207Factory.newMessage(V0207.PantsMessage);
((com.mydomain.clothesmessage.v0207.messagedefinitions.Pants)pantsMessage).getZipperType();
or
Message sockMessage = V0207Factory.newSock();
((com.mydomain.clothesmessage.v0207.messagedefinitions.Socks)sockMessage).getSmellLevel();
What are your thoughts? I'm using JDK 1.7, but 1.8 might be usable.
Consider using the factory design pattern with interfaces. The version of Java that you use does not make a difference (though support for Java 7 goes away in the spring, April if I remember correctly).
Define an interface for each class containing the method signatures that will be implemented by all the versions of the class.
Update your class definitions to include the appropriate interface definition.
Create a class factory for each needed class, passing it the information needed to create the appropriate version of the class. This class factory should return the interface type for the created class.
Here is an example:
TestPants
public class TestPants {
IPants pants = PantsFactory.PantsFactory(207);
Message zipperType = pants.getZipperType();
Message color = pants.getColor();
)
}
IPants
public interface IPants {
Message getZipperType();
Message getColor();
}
Pants
public class Pants implements IPants {
// Class fields and Object fields
#Override
public Message getColor () {
return null;
}
#Override
public Message getZipperType () {
return null;
}
// implement any common methods among all versions
}
PantsV0105
public class PantsV0105 extends Pants {
// add changes for this version
}
PantsV0207
public class PantsV0207 extends Pants {
// add changes for this version
}
PantsFactory
public class PantsFactory {
public static IPants PantsFactory(int version) {
switch (version) {
case 105: return new PantsV0105(); break;
case 207: return new PantsV0207(); break;
default: return null;
}
}
I initially solved this by using inner static classes in one gigantic "version" class. Thus, the use looked like this:
V0207.Pants pantsMessage = new V0702.Pants();
But the version class ('V0207') grew too quickly, especially as other developers on the team demanded a more "Java" way of setting the fields (which required a lot of getters and setters).
Thus, the final solution is to put the messages inside their own v0207.messages package name, and prepend each message with the version:
V0207_Pants pantsMessage = new V0702_Pants();
It's not as nice as using a C++ namespace, but it works. The version is clear to the reader, and the object can contain a lot of code without any files becoming too large.

Prototyping in Java instead of extending

Is Javascript-like prototyping anyhow achievable, even using Reflection? Can I wrap my object inside another one, just to extend its functionality with one or two more methods, without wiring all its original nonprivate methods to the wrapper class, or extends is all I get?
If you are looking for extension methods, you could try Xtend. Xtend is language that compiles to java code and eliminates boilerplate code.
The following text is stolen from the Xtend Docs for extensions:
By adding the extension keyword to a field, a local variable or a parameter declaration, its instance methods become extension methods.
Imagine you want to have some layer specific functionality on a class Person. Let us say you are in a servlet-like class and want to persist a Person using some persistence mechanism. Let us assume Person implements a common interface Entity. You could have the following interface
interface EntityPersistence {
public save(Entity e);
public update(Entity e);
public delete(Entity e);
}
And if you have obtained an instance of that type (through a factory or dependency injection or what ever) like this:
class MyServlet {
extension EntityPersistence ep = Factory.get(typeof(EntityPersistence))
...
}
You are able to save, update and delete any entity like this:
val Person person = ...
person.save // calls ep.save(person)
person.name = 'Horst'
person.update // calls ep.update(person)
person.delete // calls ep.delete(person)
I don't think you can do this in Java. You can though in Groovy, using metaclasses
String.metaClass.world = {
return delegate + " world!"
}
println "Hello".world()

What does `Client.findById(id)` mean?

Looking through the Play documentation for Java I noticed the following block of code:
public static Result show(Long id) {
Client client = Client.findById(id);
return ok(views.html.Client.show(client));
}
Source: http://www.playframework.com/documentation/2.1.0/JavaRouting
I am having some trouble understanding the second line, my understanding of Java Object creation is a typical constructor looks like the following:
Person john = new Person();
What is the second line doing? Creating a Object called client from Class called Client, also what is Client? It doesn't appear to be a part of the Play Framework, certainly I cannot find anything in JavaDocs.
Thanks
Edit:
I found this to be a good point of reference for the answer (http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html)
Also I think the class Client comes from the following documentation (http://www.playframework.com/documentation/1.1.1/controllers) with Client being just a example model class, the new documentation probably needs updating to clear up this confusion.
Pretty clearly, the class Client has a static function of findById, which takes a Long and returns a Client. Static functions are functions that are defined without any access to object properties, and therefore can be accessed through the class name, rather than having to be accessed through an object. Most likely, the class has a static property containing a collection of all clients in the system by index, and findById grabs an existing Client from that list.
I really have no idea where the class Client is defined, however. I've also made a quick look around for it, and couldn't find it in the obvious places.
There must be a static method called show(Client) on the views.html.Client class that returns some object. That object is passed into an ok(whatever) method, and that ok method returns a Result object.
You're missing some basic knowledge/experience. The sample you gave has nothing to do with routes and in this snippet only first line is important, second is just some hypothetical usage. De facto it could be just...
public static Result show(Long id) {
return ok("You want to display details of client with ID: " + id);
}
Although #BenBarden explained what is that mean correctly , this static method isn't declared anywhere, it's (again) hyphotetical usage of some ORM. For an example the real usage with Ebean's model will be:
Client = Client.find.byId(id);
Of course you can also declare own method in your Client model and name it the same as in the sample, however it will be just only wrapper:
public static Finder<Long, Client> find
= new Finder<>(Long.class, Client.class);
public Client findById(Long id) {
return find.byId(id);
}
Conclusions
You need to examine some samples available with your Play sources to get familiar with some basic syntax, fortunately you'll find it easy.
DO NOT MIX documentation from Play 1.x with Play 2.x they are not compatible!

Categories