I try to do something strange may be. My vision:
I need a standard architecture with controllers, services and other layers.
I need clients for my controllers that I can distrubute separate.
And I wrote something like this:
module-api
module-impl
Module-api contains only OpenFeign clients like:
#FeignClient(path = TopLevelClient.ROOT_PATH)
public interface TopLevelClient implements CommonInterfaceForClient<EntityDto> {
String ROOT_PATH = "/entity";
#GetMapping
ResponseEntity<EntityDto> getAll();
}
Module-impl contains controllers and other logic like:
#RestController
#RequestMapping(TopLevelClient.ROOT_PATH)
public class TopLevelController implements TopLevelClient {
String ROOT_PATH = "/entity";
#Override
#GetMapping
ResponseEntity<List<EntityDto>> getAll() {...}
}
And of course I have a some strange common parametrized interace like this:
CommonInterfaceForClient
Okay, that's all right. But it's ok only for an one level REST path. I mean
/entity/{id}
But I need to request sub level:
/entitiy/{id}/sub-entity/{subId}
And I can image how I have to do this. I can't implements two interfaces at once cause first interface parametrized with an other DTO. I can't use method for calculate a mapping path cause a value must be a constant.
I mean I want to do something like this:
#FeignClient(path = SubLevelClient.ROOT_PATH)
public class SubLevelClient implements ... {
String ROOT_PATH = "/entity/{entityId}/sub-entity";
#GetMapping
ResponseEntity<List<SubEntityDto>> getAll(#PathVariable long entityId);
}
May be you can tell me something useful or may be something from the best practice?
I just want to take few common interfaces, services and controllers/clients for common actions but I want to write with one's own hands. Or may be it's a stupid idea and you can tell me a turnkey solution.
Related
I've been reading the camel documentation and looking for samples regarding CamelProxy and #Produce, trying to figure if it possible to produce payloads for multiple routes from the same proxy.
To get a better grasp of the concept, let's suppose we have the following interface:
public interface UserServiceTransport {
void save(User user);
User load(String userId);
}
Would it be possible have a proxy injected in a POJO, and calling one the 2 methods would kick-start the appropriate route?
Perhaps I've missed or misunderstood something from the docs... I'm trying to reuse some legacy code in a new application, and all the samples I've seen so far either have interfaces with 1 method or more overloaded methods, eg:
public class UserService {
#Produce(uri = "direct:save_user")
protected UserServiceTransport transport;
public void save(User user) {
transport.save(user)
}
}
Unfortunately this is not helpful in my case because I'd have to create many interfaces and classes.
Alternatively, is there any other way I can call a few routes from a POJO?
This is one of those topics I don't even know how to search in google (tried already, most of the results were for C#), so here I go:
I'm messing around with our huge application, trying to get to work a brand new DAO/Entity/Service/DTO.. euh...thing. I've been left more or less on my own, and, again, more or less, I'm getting to understand some of the hows and maybe one or two of the whys.
The thing is that I got all, the way "up", from the DB to the Service:
I got a DAO class which executes a query stored on an Entity class. After executing it, it returns the Entity with the values.
The service receives the Entity and, somehow, transforms the Entity to a DTO and returns it to whenever is needed.
My problem is with the "somehow" thing the code goes like this:
DTOClass dto = ClassTransformerFromEntityToDTO.INSTANCE.apply(entityQueryResult);
I went into ClassTransformerFromEntityToDTO and found this:
public enum ClassTransfomerFromEntityToDTO implements Function<EntityClass,DTO Class> ) {
INSTANCE;
#Override
public DTOClass apply(EntityClass entityInstance) {
/*Code to transform the Entity to DTO and the return*/
}
}
The class that this... thing, implements, is this:
package com. google .common . base;
import com. google .common . annotations. GwtCompatible ;
import javax. annotation .Nullable ;
#GwtCompatible
public abstract interface Function <F , T >
{
#Nullable
public abstract T apply (#Nullable F paramF) ;
public abstract boolean equals (#Nullable Object paramObject) ;
}
I'm in the classic "everyone who where at the beginning of the project fled", and no one knows why is this or what is this (The wisest one told me that maybe it had something to do with Spring), so, I have two main questions (which can be more or less answered in the same side):
1) What's this? What's the point of using an enum with a function to make a conversion?
2) What's the point of this? Why can I just make a class with a single function and forget about this wizardry?
not sure there's much to answer here... And I'm adding an answer to illustrate my thoughts with some code I've seen, but that you have is horrible. I've actually seem similar stuff. My guess is that that codes actually precedes Spring. It's used as some sort of Singleton.
I have seen code like this, which is worse:
public interface DTO {
find(Object args)
}
public class ConcreteDTO1 implements DTO {
...
}
public class ConcreteDTO2 implements DTO {
...
}
public enum DTOType {
CONCRETE_DTO1(new ConcreteDTO1(someArgs)),
CONCRETE_DTO2(new ConcreteDTO2(someOtherArgs))
private DTO dto;
public DTOType(DTO dto) {
this.dto = dto;
}
public DTO dto() {
return dto;
}
}
and then the DTOs are basically accessed through the Enum Type:
DTOType.CONCRETE_DTO1.dto().find(args);
So everyone trying to get hold of a DTO accesses it through the enum. With Spring, you don't need any of that. The IoC container is meant to avoid this kind of nonsense, that's why my guess is that it precedes Spring, from some ancient version of the app when Spring was not there. But it could be that someone was wired to do such things regardless of whether Spring was already in the app or not.
For that kind of stuff you're trying to do, you're better of with the Visitor pattern. Here's an example from a different answer: passing different type of objects dynamically on same method
It's me. From the future.
Turns out that this construct is a propossed Singleton Implementation, at least on "Effective Java 2nd edition".
So, yeah, Ulise's guess was well oriented.
I am working on GWT project with JDK7. It has two entryPoints (two clients) that are located in separate packages of the project. Clients share some code that is located in /common package, which is universal and accessible to both by having the following line in their respective xml-build files:
<source path='ui/common' />
Both clients have their own specific implementations of the Callback class which serves their running environments and performs various actions in case of failure or success. I have the following abstract class that implements AsyncCallback interface and then gets extended by its respective client.
public abstract class AbstractCallback<T> implements AsyncCallback<T> {
public void handleSuccess( T result ) {}
...
}
Here are the client's classes:
public class Client1Callback<T> extends AbstractCallback<T> {...}
and
public class Client2Callback<T> extends AbstractCallback<T> {...}
In the common package, that also contains these callback classes, I am working on implementing the service layer that serves both clients. Clients use the same back-end services, just handle the results differently. Based on the type of the client I want to build a corresponding instance of AbstractCallback child without duplicating anonymous class creation for each call. I am going to have many declarations that will look like the following:
AsyncCallback<MyVO> nextCallback = isClient1 ?
new Client1Callback<MyVO>("ABC") {
public void handleSuccess(MyVO result) {
doThatSameAction(result);
}
}
:
new Client2Callback<MyVO>("DEF") {
public void handleSuccess(MyVO result) {
doThatSameAction(result);
}
};
That will result in a very verbose code.
The intent (in pseudo-code) is to have the below instead:
AsyncCallback<MyVO> nextCallback = new CallbackTypeResolver.ACallback<MyVO>(clientType, "ABC"){
public void handleSuccess(MyVO result) {
doThatSameAction(result);
}
};
I was playing with the factory pattern to get the right child instance, but quickly realized that I am not able to override handleSuccess() method after the instance is created.
I think the solution may come from one of the two sources:
Different GWT way of dealing with custom Callback implementations, lets call it alternative existent solution.
Java generics/types juggling magic
I can miss something obvious, and would appreciate any advice.
I've read some articles here and on Oracle about types erasure for generics, so I understand that my question may have no direct answer.
Refactor out the handleSuccess behavior into its own class.
The handleSuccess behavior is a separate concern from what else is going on in the AsyncCallback classes; therefore, separate it out into a more useful form. See Why should I prefer composition over inheritance?
Essentially, by doing this refactoring, you are transforming an overridden method into injected behavior that you have more control over. Specifically, you would have instead:
public interface SuccessHandler<T> {
public void handleSuccess(T result);
}
Your callback would look something like this:
public abstract class AbstractCallback<T> implements AsyncCallback<T> {
private final SuccessHandler<T> handler; // Inject this in the constructor
// etc.
// not abstract anymore
public void handleSuccess( T result ) {
handler.handleSuccess(result);
}
}
Then your pseudocode callback creation statement would be something like:
AsyncCallback<MyVO> nextCallback = new CallbackTypeResolver.ACallback<MyVO>(
clientType,
"ABC",
new SuccessHandler<MyVO>() {
public void handleSuccess(MyVO result) {
doThatSameMethod(result);
}
});
The implementations of SuccessHandler don't have to be anonymous, they can be top level classes or even inner classes based on your needs. There's a lot more power you can do once you're using this injection based framework, including creating these handlers with automatically injected dependencies using Gin and Guice Providers. (Gin is a project that integrates Guice, a dependency injection framework, with GWT).
I'm a huge fan of Java's annotations, but find it a pain in the neck to have to include Google's Reflections or Scannotations every time I want to make my own.
I haven't been able to find any documentation about Java being able to automatically scan for annotations & use them appropriately, without the help of a container or alike.
Question: Have I missed something fundamental about Java, or were annotations always designed such that manual scanning & checking is required? Is there some built-in way of handling annotations?
To clarify further
I'd like to be able to approach annotations in Java a little more programatically. For instance, say you wanted to build a List of Cars. To do this, you annotate the list with a class that can populate the list for you. For instance:
#CarMaker
List<Car> cars = new List<Car>();
In this example, the CarMaker annotation is approached by Java, who strikes a deal and asks them how many cars they want to provide. It's up to the CarMaker annotation/class to then provide them with a list of which cars to include. This could be all classes with #CarType annotations, and a Car interface.
Another way of looking at it, is that if you know you want to build something like this: List<Car> cars, you could annotate it with #ListMaker<Car>. The ListMaker is something built into Java. It looks for all classes annotated with #CarType, and populates the list accordingly.
You can create your own annotations and apply them to your own classes.
If you specify that an annotation is detectable at runtime, you can process it easily with reflection.
For example, you could use something like this to print the name of each field in a class that has been marked with the Funky annotation:
for (Field someField : AnnotatedClass.getClass().getDeclaredFields()) {
if (someField.isAnnotationPresent(Funky.class)) {
System.out.println("This field is funky: " + someField.getName());
}
}
The code to declare the Funky annotation would look something like this:
package org.foo.annotations;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Funky { }
Here's a class that uses the annotation:
package org.foo.examples;
import org.foo.annotations.Funky;
public class AnnotatedClass {
#Funky
private String funkyString;
private String nonFunkyString;
#Funky
private Integer funkyInteger;
private Integer nonFunkyInteger;
}
Here's some more reading on Annotations.
Here are the javadocs for the classes used above:
Retention annotation
RetentionPolicy enum
Target annotation
Field class
isAnnotationPresent() method
getDeclaredFields() method
I'm trying to understand your car example, but I'm not sure I follow what you want.
If you had a list of objects (Jaguar, Porche, Ferrari, Kia) that extend Car and are marked with various car-related annotations, you could create an object that filters the list based on annotations.
The code might look like this:
#WorldsFinestMotorCar
class Jaguar extends Car {
// blah blah
}
#BoringCar
class Porche extends Car {
// blah blah
}
#BoringCar
class Ferrari extends Car {
// blah blah
}
#IncredibleCar
class Kia extends Car {
// blah blah
}
You could implement an AnnotationFilter class that removes cars from the list that do not have a certain annotation.
It might look something like this:
List<Car> carList = getListOfRandomCars();
AnnotationFilter<Car> annoFilter = new AnnotationFilter<Car>(BoringCar.class);
List<Car> boringCars = annoFilter.filter(carList);
Is that what you want to do?
If so, it can definitely be done.
The implementation for AnnotationFilter might look something like this:
public class AnnotationFilter<T> {
private Class filterAnno;
public AnnotationFilter(Class a) {
filterAnno = a;
}
public List<T> filter(List<T> inputList) {
if (inputList == null || inputList.isEmpty()) {
return inputList;
}
List<T> filteredList = new ArrayList<T>();
for (T someT : inputList) {
if (someT.getClass().isAnnotationPresent(filterAnno)) {
filteredList.add(someT);
}
}
return filteredList;
}
}
If that's not what you're after, a specific example would be helpful.
Java haven't got anything built in as such, which is why Reflections came about. Nothing built in that's as particular as what you're saying..
User-defined Annotations: we shall see how to annotate objects that we may come across in day-to-day life. Imagine that we want to persistent object information to a file. An Annotation called Persistable can be used for this purpose. An important thing is that we want to mention the file in which the information will get stored. We can have a property called fileName within the declaration of Annotation itself. The definition of the Persistable Annotation is given below,
Persistable.java
#Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
public #interface Persistable
{
String fileName();
}
Annotations are just a way of tagging elements of a class; how these annotations are interpreted is up to the code that defines these annotations.
Is there some built-in way of handling annotations?
Annotations are used in so many different ways that it would be difficult to come up with a few "built-in ways" of handling them. There are source-level annotations (such as #Override and #Deprecated) that do not affect the behaviour of the code at all. Then there are runtime annotations that are usually very specific to a certain library, for eg. JAXB's binding annotations only make sense within a JAXBContext and Spring's autowiring annotations only make sense within an ApplicationContext. How would Java know what to do with these annotations simply by looking at a class which uses them?
I'm developing an app with Jersey where I have many resources. Although main functionality of these resources varies, they share lots of common methods (like list, read, update and etc). The app runs on Google App Engine and uses Guice for dependency injection.
My first approach was to have a generic AbstactResource which contains all common logic, and it's respectively extended by all other resources which add their required custom methods.
public class AbstractResource<T> {
#GET
public ListPage<T> list(#QueryParam("limit") Integer limit,
#QueryParam("start") Integer start) {
// ... implementation
}
#GET
#Path("/{id}")
public T get(#PathParam("id") Long id) {
// ... implementation
}
And sample resource looks like:
public class TenantResource extends AbstractResource<Tenant> {
// custom resource related methods here
}
Everything works fine in this case. The problems appear when I add one more level of abstraction. Let's say if I want to store history and changelogs only for some of my resources. I've created one more abstract class extending AbstractResource called AudiatableResource which adds the required functionality.
public abstract class AuditableResource<T extends AuditableModel>
extends AbstractResource {
// here I override update and create methods to save changelogs
}
As you see the type parameter in this case has changed (now it extends AuditableModel).
New concrete resources will look like:
public class PropertyResource extends AuditableResource<Tenant> {
// custom resource related methods here
}
In this case everything still works, but this time I'm getting lots of warning messages on start-up:
WARNING: Return type T of method public T com.pkg.AbstractResource.get(java.lang.Long) is not resolvable to a concrete type
WARNING: Return type T of method public T com.pkg.AbstractResource.getNew() is not resolvable to a concrete type
WARNING: Return type com.pkg.data.ListPage<T> of method public com.pkg.ListPage<T> com.pkg.AbstractResource.list(java.lang.Integer,java.lang.Integer) is not resolvable to a concrete type
I really wonder if this approach is correct using Jersey and if I can just ignore this messages. It would be interesting to know how resources are organized in cases when there are large number of them.
One way to go is to separate the definition of the resources from the implementation.
Have very simple resource classes, defining the different services you want to offer. This way, the API you expose through rest is easily located and audited. The different methods are probably delegates to an implementation class
Implement the business logic of your resources in the implementations, where you might want to use inheritance to factor common behavior.
The reason you get those messages at runtime is that jersey uses runtime information about types in the resource. Generic type information being erased at compile time, it cannot get the actual return type of the generic class methods. If you provide a REST "facade" to your implementation, you can make this explicit.
public class Facade {
private final PropertyResource propertyResource;
public Facade() {
propertyResource = new PropertyResource();
}
#GET
#Path("somepath")
public Tenant something() {
return propertyResource.something();
}
}