0
\$\begingroup\$

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;
    }   

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.