Where to instantiate object on clean architecture

I am trying to wrap my head around clean architecture but I am struggling with the concept of how to avoid some dependencies.

I am implementing an API in Java for personal use, however I was trying to find some examples and came across this post: https://android.jlelse.eu/a-complete-idiots-guide-to-clean-architecture-2422f428946f

I’ve checked out the project and was checking the implementation until one thing bothered me and that was on how objects get instantiated.

The data layer and domain layer both seemed pretty devoid of problems. Data and models are separated and use Interfaces to talk to one another. As of my understanding the data layer and presentation are both on the “outer rings”, i.e. on a same level, but I thought they should be completely independent. However, in this project, in the presentation layer all instantiation from all necessary objects happen. they get passed it to the domain layer or even data layer. (this happens on the TownshipListActivity.java if you are curious)

This seems to me to make little sense. You would end up coupling your view with your data layer. Yes I agree that the domain layer is still wild and free, but is this correct?

Else where should these be created? In my application I started to play with the idea of having a context object that creates them all but somehow this also feels fishy to me…

Given a resource ID, instantiate, retrieve and localize a Linked Resource for a REST API call

During a question on Stack Overflow, another user had some comments about the way this code works. He had a few choice words for it, including “magic”, “ugly contraption”, “you’re doing things you shouldn’t be doing”. I wanted to ask some feedback on this sytem. Note: there might be some minor things in here like superclass properties and constants that aren’t included. I’ve also removed country, company and product names wherever possible.

the biggest question I have is whether I’m not abusing the interaction between the @Component and @PostConstruct tags to initialize the MasterCodeView lists. I feel like this was the biggest concern of the SO user who was confused about this system.

XmlBaseChild.java:

package client.rest.view.base;  import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map;  import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.util.UriTemplate;  import business.shared.bs.login.LoginView; import business.shared.bs.mastercode.MasterCodeService; import business.shared.bs.mastercode.MasterCodeView; import client.rest.exception.NotFoundException; import client.rest.exception.RestAuthenticationException; import client.rest.interfaces.RestChildResourceNameable; import client.rest.link.Link; import client.struts2.containers.UserContainer; import util.constants.MessageKeys; import util.i18n.ResourceBundleUtil;  import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty;  @JsonIgnoreProperties(value={"factoryName","factoryTitle","viewName","viewTitle","factoryNameChild","factoryTitleChild","viewNameChild","viewTitleChild"}) public abstract class XmlBaseChild implements RestChildResourceNameable {  private static final long serialVersionUID = 1L;  protected HttpServletRequest request;  public abstract String getFactoryName(); public abstract String getFactoryTitle(); public abstract String getViewName(); public abstract String getViewTitle();  public abstract String getFactoryNameChild(); public abstract String getFactoryTitleChild(); public abstract String getViewNameChild(); public abstract String getViewTitleChild();  private List<Link> links = new ArrayList<Link>();  protected Integer value; protected String text;  @Autowired transient protected MasterCodeService masterCodeService;  /**  * Constructor during Unmarshalling (from xml/json to java objects).  */ public XmlBaseChild() {     super(); }  /**  * Constructor for creating this object and preparing for marshalling (from java objects to xml/json).  * @param value         Numeric value of the ChildView  * @param request       HttpServletRequest  * @param includeSelf   Include SELF link  * @param includeUP     Include UP link  */ public XmlBaseChild(Integer value, HttpServletRequest request, boolean includeSelf, boolean includeUP) {     super();     setRequest(request);     setValue(value); }  /**  * @return the HttpServletRequest  */ @JsonIgnore @XmlTransient public HttpServletRequest getRequest() {     return request; }  /**  * @param request the HttpServletRequest to set  */ @JsonIgnore public void setRequest(HttpServletRequest request) {     this.request = request; }  @JsonInclude(Include.NON_NULL) @JsonProperty(value="links") @XmlElement(name = "link") public List<Link> getLinks() {     return links; }  @JsonInclude(Include.NON_NULL) @JsonProperty(value="links") public void setLinks(List<Link> links) {     this.links = links; }  public void addLink(Link link) {     links.add(link); }  public void clearLinks() {     links.clear(); }  @JsonProperty(value="id") @XmlElement(name="id") public Integer getValue() {     return this.value; }  /**  * Set the Numeric value of the ChildView.  * This code is common for all childViews and handles a null value.  * @param value Numeric value of the ChildView  */ @JsonProperty(value="id") public void setValue(Integer value) {     if (value == null) {             this.value = null;             this.text = null;             return;     }     setConcreteValue(value); }  /**  * Set the Numeric value of the ChildView.  * This code must be overridden by the concrete childViews.  * @param value Numeric value of the ChildView  */ protected void setConcreteValue(Integer value){     boolean keyNotFound = true;     if (value != null && value > -1) {         this.value = value;         String messageKey = getMessageKey(value, GetMasterCodeMapForChildView());         if (messageKey != null) {             this.text = ResourceBundleUtil.getResourceBundleText(messageKey, null, new Locale(getISO639LanguageCode()));             keyNotFound = false;         }     }     if (keyNotFound){         throw new NotFoundException(ResourceBundleUtil.getResourceBundleText(MessageKeys.ERROR_REST_MASTER_CODE_NOT_FOUND_EXCEPTION, new Object[]{getViewNameChild(), value}, new Locale(getISO639LanguageCode())));     } }  protected abstract Map<String, MasterCodeView> GetMasterCodeMapForChildView();  /**  * Textual representation of this childView.  * @return  text  */ @JsonProperty(value="text") @XmlElement(name="text") public String getText() {     return this.text; }  /**  * Text is a read-only field. It is set by setValue().  * The client should't set the text but rather the value.  * @param text  */ @JsonProperty(value="text") public void setText(String text){};  /**  * Get the base URL of REST web services from the request URL,  * e.g. http://localhost:8080/alm/rest/v1  * @return The base REST URL.  */ protected String getBaseUrl() {     String url = getRequestURL();     String baseUrl = String.format( "%s%s", (url.split("/rest/"))[0], "/rest/v1/ );     return baseUrl; }  /**  * Get the request URL.  * @param request  HttpServletRequest  * @return The request URL.  */ protected String getRequestURL() {     return getRequest().getRequestURL().toString(); }  /**  * Get the loginView from the session.  * @return  loginView  */ protected LoginView getLoginView() {     UserContainer userContainer = (UserContainer) getRequest().getSession().getAttribute(UserContainer.DEFAULT_SESSION_ATTRIBUTE);     boolean isLoggedOn = (userContainer != null && userContainer.getLoginView() != null);     if (!isLoggedOn) {         throw new RestAuthenticationException();     } else {         return userContainer.getLoginView();     } }  protected String getISO639LanguageCode() {     try {         return getLoginView().getLocale().getLanguage();     } catch (Exception e) {         // Possible missing request object when unmarchalling a JSON string during unit tests.         return "en";     } }  /**  * Utility which converts a List of MasterCodeView objects  * to a map (key = code).  *   * @param   list    a list of MasterCodeView objects  * @return  a map of MasterCodeView objects  */ //TODO: copied from the struts2 fieldformatter, can this be placed in some utility class? protected Map<String, MasterCodeView> convertListToMap(List<MasterCodeView> list) {     Map<String, MasterCodeView> map = new HashMap<String, MasterCodeView>();     Iterator<MasterCodeView> iterator = list.iterator();     while (iterator.hasNext()) {         MasterCodeView masterCodeView = (MasterCodeView)iterator.next();         map.put(masterCodeView.getCode(), masterCodeView);     }     return map; }  /**  * Utility which returns the message key that corresponds to a code.  *   * @param code the code  * @param map the map containing the MasterCodeView objects  * @return the messageKey of the code, or null if not found  */ //TODO: copied from the struts2 fieldformatter, can this be placed in some utility class? protected String getMessageKey(Object code, Map<String, MasterCodeView> map) {     if (code != null) {         String codeStr = null;         if (code instanceof String) {             codeStr = (String) code;         }         else if (code instanceof Integer) {             codeStr = ((Integer) code).toString();         }         else if (code instanceof Boolean) {             codeStr = ((Boolean) code).toString();         }          if (codeStr != null) {             MasterCodeView masterCodeView = (MasterCodeView)map.get(codeStr);             if (masterCodeView != null) {                 return masterCodeView.getDescription();             }         }     }     return null; } 

}

Example of subclass in XmlAgentStatus.java:

package client.rest.view.machine;  import java.util.HashMap; import java.util.Map;  import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlRootElement;  import org.springframework.stereotype.Component;  import business.shared.bs.machine.MachineStatusView; import business.shared.bs.mastercode.MasterCodeView; import client.rest.view.base.XmlBaseChild;  @Component @XmlRootElement(name=XmlAgentStatus.VIEW_NAME) public class XmlAgentStatus extends XmlBaseChild{      private static final long serialVersionUID = 1L;      public static Map<String, MasterCodeView> agentStatusTypeCodes = new HashMap<String, MasterCodeView>();      public static final String FACTORY_NAME = "agentstatuses";     public static final String FACTORY_TITLE = "Agent Statuses";     public static final String VIEW_NAME = "agentstatus";     public static final String VIEW_TITLE = "Agent Status";      public String getFactoryName() { return XmlMachineView.FACTORY_NAME; }     public String getFactoryTitle() { return XmlMachineView.FACTORY_TITLE; }     public String getViewName() { return XmlMachineView.VIEW_NAME; }     public String getViewTitle() { return XmlMachineView.VIEW_TITLE; }      public String getFactoryNameChild() { return XmlAgentStatus.FACTORY_NAME; }     public String getFactoryTitleChild() { return XmlAgentStatus.FACTORY_TITLE; }     public String getViewNameChild() { return XmlAgentStatus.VIEW_NAME; }     public String getViewTitleChild() { return XmlAgentStatus.VIEW_TITLE; }       /**      * @see client.rest.view.base.XmlBaseChild#XmlBaseChild()      */     public XmlAgentStatus() {         super();     }      /**      * Constructor for creating this object and preparing for marchalling (from java objects to xml/json).      * @param view          Parent view      * @param request       HttpServletRequest      */     public XmlAgentStatus(MachineStatusView view, HttpServletRequest request) {         super(view.getStatus(), request, false, false);     }      /**      * Constructor for creating this object and preparing for marchalling (from java objects to xml/json).      * @param value         Integer value for the childView      * @param request       HttpServletRequest      */     public XmlAgentStatus(Integer value, HttpServletRequest request) {         super(value, request, false, false);     }      /**      * Constructor for creating this object and preparing for marchalling (from java objects to xml/json).      * @param view          Parent view      * @param request       HttpServletRequest      * @param includeSelf   Include SELF link      * @param includeUP     Include UP link      */     public XmlAgentStatus(MachineStatusView view, HttpServletRequest request, boolean includeSelf, boolean includeUP) {         super(view.getStatus(), request, includeSelf, includeUP);     }      /**      * Constructor for creating this object and preparing for marchalling (from java objects to xml/json).      * @param value         Numeric value of the ChildView      * @param request       HttpServletRequest      * @param includeSelf   Include SELF link      * @param includeUP     Include UP link      */     public XmlAgentStatus(Integer value, HttpServletRequest request, boolean includeSelf, boolean includeUP) {         super(value, request, includeSelf, includeUP);     }      /**      * Initialize the OperatingSystem Type codes after the component is wired (postconstruct),      * so that they are available in the constructor when an XmlOperatingSystem object is created.      */     @PostConstruct     protected void initializeMachineAgentStatusTypeCodes() {         agentStatusTypeCodes = convertListToMap(masterCodeService.getAgentStatusTypeCodes());     }      @Override     protected Map<String, MasterCodeView> GetMasterCodeMapForChildView() {         // TODO Auto-generated method stub         return agentStatusTypeCodes;     }  } 

XmlBaseChildList.java

package client.rest.view.base;  import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.List;  import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient;  import org.springframework.web.util.UriTemplate;  import client.rest.controller.base.BaseRestController; import client.rest.exception.InternalServerException; import client.rest.interfaces.RestBase; import client.rest.interfaces.RestChildResourceNameable; import client.rest.link.Link;  import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty;  @JsonIgnoreProperties(value={"factoryName","factoryTitle","viewName","viewTitle","factoryNameChild","factoryTitleChild","viewNameChild","viewTitleChild"}) public abstract class XmlBaseChildList<E extends XmlBaseChild> implements RestBase, RestChildResourceNameable {      private static final long serialVersionUID = 1L;      public abstract String getFactoryName();     public abstract String getFactoryTitle();     public abstract String getViewName();     public abstract String getViewTitle();      public abstract String getFactoryNameChild();     public abstract String getFactoryTitleChild();     public abstract String getViewNameChild();     public abstract String getViewTitleChild();      protected HttpServletRequest request;      protected List<E> childViewList = new ArrayList<E>();      public abstract List<E> getChildViewList();      /**      * Constructor during Unmarshalling (from xml/json to java objects). This      * constructor doesn't auto-generate the internal viewList (note that this      * is a read-only resource). You should generally use the constructor with      * the HttpServletRequest parameter.      */     public XmlBaseChildList() {         super();     }      /**      * This constructor is used by the REST Controllers and auto-generates the      * internal childViewList.      *       * @param request           HttpServletRequest      * @param includeSelf       Include SELF link      * @param includeUP         Include UP link      * @param includeSelfChilds Include SELF link for all included childView objects      * @param len               Number of childViews      */     public XmlBaseChildList(HttpServletRequest request, boolean includeSelf, boolean includeUP, boolean includeSelfChilds, String[][] descriptions) {         super();         setRequest(request);         autoLoadChildViews(includeSelfChilds, descriptions);     }      /**      * Autoload the childViewList. Optionally include a SELF link with every childView.      * @param includeSelfChilds If true, include a SELF link with every childView.      * @param len               Number of childViews.      */     @SuppressWarnings("unchecked")     protected void autoLoadChildViews(boolean includeSelfChilds, String[][] descriptions) {         if (descriptions.length > 0) {             Type superclass = getClass().getGenericSuperclass();             Type type = ((java.lang.reflect.ParameterizedType) superclass).getActualTypeArguments()[0];             Class<E> clazz = (Class<E>) type;             Constructor<E> xmlChildViewConstructor = null;             try {                 xmlChildViewConstructor = clazz.getConstructor(Integer.class, HttpServletRequest.class, boolean.class, boolean.class);             } catch (Exception e) {                 throw new InternalServerException("Exception when trying to get the constructor from the concrete childView class.", e);             }              for(int i = 0; i < descriptions.length; ++i) {                 try {                     E xmlChildView = xmlChildViewConstructor.newInstance(Integer.valueOf(descriptions[i][0]), request, includeSelfChilds, false);                     childViewList.add(xmlChildView);                 } catch (Exception e) {                     throw new InternalServerException("Exception when trying to instantiate the concrete childView class.", e);                 }             }         }     }      /**      * @return the HttpServletRequest      */     @JsonIgnore     @XmlTransient     public HttpServletRequest getRequest() {         return request;     }      /**      * @param request the HttpServletRequest to set      */     @JsonIgnore     public void setRequest(HttpServletRequest request) {         this.request = request;     }      @JsonProperty(value="count")     @XmlAttribute(name = "count")     public int getCount() {         return (childViewList == null) ? 0 : childViewList.size();     }      @JsonProperty(value="count")     public void setCount(int count) {         //no-op, just keep JSON unmashalling happy     }       /**      * Get the base URL of REST web services from the request URL,      * e.g. http://localhost:8080/alm/rest/v1      * @return The base REST URL.      */     protected String getBaseUrl() {         String url = getRequestURL();         String baseUrl = String.format( "%s%s", (url.split("/rest/"))[0], BaseRestController.REST_VERSION_MAPPING );         return baseUrl;     }      /**      * Get the request URL.      * @param request  HttpServletRequest      * @return The request URL.      */     protected String getRequestURL() {         return getRequest().getRequestURL().toString();     }        } 

Specific Subclass XmlAgentStatusList:

package client.rest.view.machine;  import java.util.List;  import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;  import business.shared.bs.agent.AgentDaemonService; import client.rest.view.base.XmlBaseChildList;  import com.fasterxml.jackson.annotation.JsonProperty;  @XmlRootElement(name = XmlAgentStatus.FACTORY_NAME) public class XmlAgentStatusList extends XmlBaseChildList<XmlAgentStatus> {      private static final long serialVersionUID = 1L;      public String getFactoryName() { return XmlMachineView.FACTORY_NAME; }     public String getFactoryTitle() { return XmlMachineView.FACTORY_TITLE; }     public String getViewName() { return XmlMachineView.VIEW_NAME; }     public String getViewTitle() { return XmlMachineView.VIEW_TITLE; }     public String getFactoryNameChild() { return XmlAgentStatus.FACTORY_NAME; }     public String getFactoryTitleChild() { return XmlAgentStatus.FACTORY_TITLE; }     public String getViewNameChild() { return XmlAgentStatus.VIEW_NAME; }     public String getViewTitleChild() { return XmlAgentStatus.VIEW_TITLE; }       /**      * @see client.rest.view.base.XmlBaseChildList.XmlBaseChildList()      */     public XmlAgentStatusList() {         super();     }      /**      * @see client.rest.view.base.XmlBaseChildList.XmlBaseChildList(HttpServletRequest, boolean, boolean, boolean, int)      */     public XmlAgentStatusList(HttpServletRequest request, boolean includeSelf, boolean includeUP, boolean includeSelfChilds) {         super(request, includeSelf, includeUP, includeSelfChilds, AgentDaemonService.AGENT_STATUS_CODE_DESCRIPTIONS);     }      /**      * Get all Statuses (this is a read-only).      */     @JsonProperty(value = XmlAgentStatus.FACTORY_NAME)     @XmlElement(name = XmlAgentStatus.VIEW_NAME)     public List<XmlAgentStatus> getChildViewList() {         return childViewList;     }  } 

Retrieving a list from the REST API:

@RequestMapping(value = "/agentstatuses", method = RequestMethod.GET) public  XmlAgentStatusList getAllAgentStatuses(HttpServletRequest request, HttpServletResponse response) {     addHeader_CacheControl(response, "private");     return new XmlAgentStatusList(request, true, true, true); } 

Retrieving a single agentStatus from the REST API:

@RequestMapping(value = "/agentstatuses/{id:\d+}", method = RequestMethod.GET) public  XmlAgentStatus getAgentStatuseById(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response) {     addHeader_CacheControl(response, "private");     return new XmlAgentStatus(id, request, true, true); } 

Retrieving the agentStatus of a specific machine:

XmlMachineStatusView xmlView = new XmlMachineStatusView(machineStatusView, request, true, true); 

XmlMachineStatusView.java

package client.rest.view.machine;  import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;  import com.fasterxml.jackson.annotation.JsonProperty;  import business.shared.bs.machine.MachineStatusView; import client.rest.util.EmbeddedResourceFactory; import client.rest.util.LinkedResource; import client.rest.view.base.XmlBaseView;  @XmlRootElement(name="machine") public class XmlMachineStatusView extends XmlBaseView<MachineStatusView> {      private static final long serialVersionUID = 1L;      public static final String FACTORY_NAME = "machines";     public static final String FACTORY_TITLE = "Machines";     public static final String VIEW_NAME = "machine";     public static final String VIEW_TITLE = "Machine";     private LinkedResource status;     public String getFactoryName() { return FACTORY_NAME; }     public String getFactoryTitle() { return FACTORY_TITLE; }     public String getViewName() { return VIEW_NAME; }     public String getViewTitle() { return VIEW_TITLE; }      /**      * @see client.rest.view.base.XmlBaseView#XmlBaseView()      */     public XmlMachineStatusView() {         super();     }      public XmlMachineStatusView(MachineStatusView view, HttpServletRequest request, boolean includeSelf, boolean includeUP) {         super(view, request, includeSelf, includeUP);     }      public XmlMachineStatusView(MachineStatusView view, HttpServletRequest request) {         super(view, request);     }      @Override     protected void initializeReferencedResources(MachineStatusView view, HttpServletRequest request) {         status = EmbeddedResourceFactory.newLinkedResource(this, new XmlAgentStatus(view, request));     }    } 

XmlBaseView.java

package client.rest.view.base;  import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Locale;  import javax.servlet.http.HttpServletRequest; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient;  import org.apache.commons.lang.StringUtils; import org.springframework.web.util.UriTemplate;  import business.shared.bs.base.BaseView; import business.shared.bs.login.LoginView; import client.rest.exception.InternalServerException; import client.rest.exception.RestAuthenticationException; import client.rest.interfaces.RestBase; import client.rest.interfaces.RestResourceNameable; import client.rest.link.Link; import client.struts2.containers.UserContainer; import util.i18n.ResourceBundleUtil;  import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty;  @JsonIgnoreProperties(value={"factoryName","factoryTitle","viewName","viewTitle","viewTitleLocalized"}) @JsonInclude(Include.NON_NULL) public abstract class XmlBaseView<V extends BaseView> implements RestBase, RestResourceNameable {      private static final long serialVersionUID = 1L;      public abstract String getFactoryName();     public abstract String getFactoryTitle();     public abstract String getViewName();     public abstract String getViewTitle();      protected HttpServletRequest request;      protected V view;      private String urn;     private String eTag;     private List<Link> links = new ArrayList<Link>();      /**      * Constructor during unmarshalling (from xml/json to java objects).      */     public XmlBaseView() {         super();         setNewView();     }      /**      * Instantiate a new View object before the unmarshalling process.      */     @SuppressWarnings("unchecked")     private void setNewView() {         Type superclass = getClass().getGenericSuperclass();         Type type = ((java.lang.reflect.ParameterizedType) superclass).getActualTypeArguments()[0];         Class<V> clazz = (Class<V>) type;         Constructor<V> viewConstructor = null;         try {             viewConstructor = clazz.getConstructor();         } catch (Exception e) {             throw new InternalServerException("XmlBaseView: Exception when trying to get the constructor from the concrete view class.", e);         }         V view = null;         try {             view = viewConstructor.newInstance();         } catch (Exception e) {             throw new InternalServerException("XmlBaseView: Exception when trying to instantiate the concrete view class.", e);         }         setView(view);     }      /**      * Constructor for creating this object and preparing for marshalling (from java objects to xml/json).      * @param view          View object      * @param request       HttpServletRequest      */     public XmlBaseView(V view, HttpServletRequest request) {         this(view, request, false, false);     }      /**      * Constructor for creating this object and preparing for marshalling (from java objects to xml/json).      * @param view          View object      * @param request       HttpServletRequest      * @param includeSelf   Include SELF link      * @param includeUP     Include UP link      */     public XmlBaseView(V view, HttpServletRequest request, boolean includeSelf, boolean includeUP) {         super();         this.setView(view);         setRequest(request);         initializeReferencedResources(view, request);         if (includeSelf) {             this.includeLinkSelf();         }         if (includeUP) {             this.includeLinkUp();         }     }      /**      * Initialize foreign-key and linked resources.      * @param view          View object      * @param request       HttpServletRequest      */     protected abstract void initializeReferencedResources(V view, HttpServletRequest request);      /**      * Get a localized title for the XmlView object.      * The locale is retrieved from the loginView of the user's session.      * @return  Localized View Title.      */     protected String getViewTitleLocalized() {         return ResourceBundleUtil.getResourceBundleText("rest." + getViewName(), null, getLocaleFromLoginView());     }      /**      * Get a localized title for the XmlView object.      * The locale is retrieved from the loginView of the user's session.      * This is a utility method that can be safely called from an uninitialized XmlBaseView or one of it's sub-types.      * @param request   HttpServletRequest      * @return          Localized View Title.      */     public String getViewTitleLocalized(HttpServletRequest request) {         UserContainer userContainer = (UserContainer) request.getSession().getAttribute(UserContainer.DEFAULT_SESSION_ATTRIBUTE);         boolean isLoggedOn = (userContainer != null && userContainer.getLoginView() != null);         if (!isLoggedOn) {             throw new RestAuthenticationException();         } else {             LoginView loginView = userContainer.getLoginView();             return ResourceBundleUtil.getResourceBundleText("rest." + getViewName(), null, new Locale(loginView.getLocale().getLanguage()));         }     }      /**      * Get the base URL of REST web services from the request URL,      * e.g. http://localhost:8080/alm/rest/v1      * @return The base REST URL.      */     protected String getBaseUrl() {         String url = getRequestURL();         String baseUrl = String.format( "%s%s", (url.split("/rest/"))[0], RestBase.REST_VERSION_MAPPING );         return baseUrl;     }      /**      * Get the request URL.      * @param request  HttpServletRequest      * @return The request URL.      */     protected String getRequestURL() {         return getRequest().getRequestURL().toString();     }      protected LoginView getLoginView() {         UserContainer userContainer = (UserContainer) getRequest().getSession().getAttribute(UserContainer.DEFAULT_SESSION_ATTRIBUTE);         boolean isLoggedOn = (userContainer != null && userContainer.getLoginView() != null);         if (!isLoggedOn) {             throw new RestAuthenticationException();         } else {             return userContainer.getLoginView();         }     }      /**      * Get the ISO639 Language Code of the user's locale associated with the      * current request.      *       * @return          ISO639 Language Code      */     protected String getISO639LanguageCode() {         return getLoginView().getLocale().getLanguage();     }      /**      * Get the Locale from the user's loginView.      * @return  locale      */     protected Locale getLocaleFromLoginView() {         Locale locale = new Locale(getLoginView().getLocale().getLanguage());         return locale;     }     } 

Sign In – following upgrade from 2.3.0 to 2.3.1 – Fatal error: Uncaught Error: Cannot instantiate interface

If you Sign In to your account and then Sign Out again whilst on the Home page or Category Page you get the following error :- Fatal error: Uncaught Error: Cannot instantiate interface Magento\Shipping\Model\CarrierFactoryInterface in /var/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:116 Stack trace: #0

If you Sign In when on a product page the error occurs straight away.

This started after updating from v2.3.0 to v2.3.1

Initially on updating I had to disable several Magento modules that were causing the following error when running the command to Re-index

PHP Fatal error: Uncaught Error: Cannot instantiate interface Magento\InventoryIndexer\Model\StockIndexTableNameResolverInterface in /var/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php:116 Stack trace: #0

I solved the reindex issue by disabling a number of modules in config.php

I am assuming my current Sign In issue is similar but I’m not sure what to disable.

I have tried the usual commands to Update and Compile with no result.

Does anyone know what modules could be related to the error – Cannot instantiate interface Magento\Shipping\Model\CarrierFactoryInterface?

Cannot instantiate interface DrupalStreamWrapperInterface

I am trying to replace drupal_realpath with realpath. What I did is

$  stream_wrapper = new DrupalStreamWrapperInterface(); $  file_path = $  stream_wrapper->realpath($  img_path); 

But it gives me this error: Cannot instantiate interface DrupalStreamWrapperInterface. Any idea how do I use DrupalStreamWrapperInterface::realpath?

Factory to instantiate and configure Selenium WebDriver?

I, also, need to know whether this is a valid implementation of the factory pattern.

The amount of effort which goes into configuring DriverFactory to simply get a WebDriver instance seems disproportionate to the point where I ask: “is there not a better way?”

The main-class code:

package dur.bounceme.net.SeleniumBase;  import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; import org.openqa.selenium.WebDriver;  public class App {      private static final Logger LOG = Logger.getLogger(App.class.getName());     private Properties properties = new Properties();      public static void main(String[] args) throws IOException {         new App().initSelenium();     }      private void initSelenium() throws IOException {         properties.loadFromXML(App.class.getResourceAsStream("/selenium.xml"));         WebDriver webDriver = DriverFactory.getWebDriver(properties);  //is this factory and usage correct?         HomePage homePage = new HomePage(webDriver);         homePage.populateCatalogue();     } } 

And my factory:

package dur.bounceme.net.SeleniumBase;  import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions;  public class DriverFactory {      private static final Logger LOG = Logger.getLogger(DriverFactory.class.getName());      private Properties properties = new Properties();     private FirefoxBinary firefoxBinary = null;     private FirefoxOptions firefoxOptions = null;     private WebDriver webDriver = null;     private URL url = null;     private String driver = null;     private String gecko = null;     private final List<String> commandLineOptions = new ArrayList<>();      private DriverFactory() {     }      private DriverFactory(Properties properties) throws MalformedURLException {         this.properties = properties;         loadProps();         init();     }       static WebDriver getWebDriver(Properties properties) throws MalformedURLException {         DriverFactory driverFactory = new DriverFactory(properties);         return driverFactory.webDriver;     }      private void loadProps() throws MalformedURLException {         LOG.fine(properties.toString());         url = new URL(properties.getProperty("url"));         driver = properties.getProperty("driver");         gecko = properties.getProperty("gecko");         String commandLineOption = properties.getProperty("option01");         commandLineOptions.add(commandLineOption);     }      private void init() throws MalformedURLException {         firefoxBinary = new FirefoxBinary();         commandLineOptions.forEach((commandLineOption) -> {             LOG.fine(commandLineOption.toString());             firefoxBinary.addCommandLineOptions(commandLineOption);         });         System.setProperty(driver, gecko);         firefoxOptions = new FirefoxOptions();         firefoxOptions.setBinary(firefoxBinary);         webDriver = new FirefoxDriver(firefoxOptions);         webDriver.get(url.toString());         LOG.fine(webDriver.getTitle());         LOG.fine(webDriver.getCurrentUrl().toLowerCase());     }      void close() {         webDriver.close();     }  } 

There seems no nice way to get around loading configuration from a file, which is then loaded. But, it strikes me that I’m re-inventing the wheel of loading a props file for the purpose of configuring a Selenium WebDriver when I expect there’s a tried-and-true approach.

Or, at least, more re-usable.

Although, what possible use there would be for multiple WebDriver instances is beyond me. It would seem Selenium Grid would handle that question quite differently.

Instantiate Controller with Interface not concrete class

As background, I am rebuilding some old code and want to wrap all the curl based requests in an interface (HttpRequestInterface) so I can swap that out later without having to write all the api calls right now.

I am trying to pass the HttpRequestInterface into controller, but it keeps saying `

TypeError: Argument 1 passed to Drupal\my_api\Controller\MyController::__construct() must be an instance of Drupal\my_api\Controller\HttpRequestInterface, instance of Drupal\my_api\Services\HttpRequest\CurlRequest given

I am new to Drupal from the .Net world and love how this functionality is out of the box and it seems like I am following the examples and code I find in core, but obviously I am missing something.

***One thing that sticks out is that this error message has the wrong namespace for HttpRequestInterface.

Below are the relevant files, I have only included what I think is pertinent to the issue, more can be made available.

Controller:

<?php  namespace Drupal\my_api\Controller;  use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Response; use Drupal\my_api\Controller\BaseApiController;  /**  * Controller routines for Api routes.  */ class RallyBoundController extends BaseApiController { 

`BaseController:

namespace Drupal\my_api\Controller;  use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Controller\ControllerBase; use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;  /**  * BaseApiController abstracts away common api concerns.  */ abstract class BaseApiController extends ControllerBase {   protected $  httpService;    /**    * Contructor requires HttpRequest Service.    *    * @param HttpRequestInterface $  httpService    *   Implementation of HttpRequestInterface defined in services.yml.    */   public function __construct(HttpRequestInterface $  httpService) {     $  this->httpService = $  httpService;   }    /**    * Get the HttpRequest implemention as interface so we can swap out as needed.    */   public static function create(ContainerInterface $  container) {     return new static(       $  container->get('my_api.httprequest')     );   } 

Service.yml:

services:   my_api.httprequest:     class: Drupal\my_api\Services\HttpRequest\CurlRequest 

HttpRequestInterface:

namespace Drupal\my_api\Services\HttpRequest;  /**  * HttpRequestInterace defines interface for making Http GET Requests.  */ interface HttpRequestInterface { 

CurlRequest:

namespace Drupal\my_api\Services\HttpRequest;  use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;  /**  * HttpRequest Implementation of HttpRequestInterface using CURL.  */ class CurlRequest implements HttpRequestInterface { 

Thanks for the help.

Instantiate a class with two parents

Suppose I have TypeA and TypeB classes, which are totally different, but both hold an list of TypeC objects.

Class TypeA { List<TypeC> cs; } Class TypeB { List<TypeC> cs; } 

Throuth all of it’s life cycle, a TypeC instance is belong to a one single TypeA instance and a one single TypeB instance, which cannot be changed.

My question is how to create a new TypeC instance and associate it to TypeA and TypeB instances?

simple solution would be:

ConstructorOfC(typeA, typeB) {     typeA.insertC(this);     typeB.insertC(this); } 

the drawbacks of this approach is that C is aware and depend on TypeA and TypeB classes. I also expose an insert method, which I do not want since insert should be only upon creation, but this method can be called at any time.

Another solution can be:

TypeA: createTypeC() {      this.cs.insert(new TypeC()); } 

which would work if typeC had a single parent, but it’s not the case.