package <%=@package%>.assembler; <%=@licence%> import <%=@package%>.model.BaseEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.hateoas.Link; import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.mvc.IdentifiableResourceAssemblerSupport; import org.springframework.stereotype.Component; import java.lang.reflect.InvocationTargetException; /** * A common base class for assembler. * @author <%=@user_name%> */ @Component public abstract class BaseAssembler extends IdentifiableResourceAssemblerSupport { protected Class resourceTypeClass; public BaseAssembler(Class controllerClass, Class resourceType) { super(controllerClass, resourceType); this.resourceTypeClass = resourceType; } @Autowired LoadBalancerClient loadBalancerClient; /** * Adds a link for the given service to the given resource. * @param resource the resource you want to add the link to. * @param serviceName the name of the service. * @param subUri the path the resource is located. * @param ref the ref of the link. */ public void linkToService(ResourceSupport resource, String serviceName, String subUri, String ref) { ServiceInstance instance = loadBalancerClient.choose(serviceName); if (instance != null) { resource.add(new Link(instance.getUri().toString() + "/" + subUri,ref)); } } /** * Adds a link for the given service to the given resource. * @param resource the resource you want to add the link to. * @param serviceName the name of the service. * @param ref the ref of the link. */ public void linkToService(ResourceSupport resource, String serviceName, String ref) { ServiceInstance instance = loadBalancerClient.choose(serviceName); if (instance != null) { resource.add(new Link(instance.getUri().toString(),ref)); } } @Override protected D instantiateResource(T entity) { try { return resourceTypeClass .getConstructor(entity.getClass()) .newInstance(entity); } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException e) { throw new RuntimeException( "Resource does not have an appropriate constructor!", e); } } }