Sirmyself
Sirmyself

Reputation: 1564

How to get a PortletPreferences without a request object

I need to start a TimerTask that uses a PortletPreferences object.

here's what I have for now (MyUpdateTask here extends TimerTask):

@ManagedBean(name = "myManagedBean", eager = true)
@ApplicationScoped
public class MyManagedBean implements Serializable {
    static MyUpdateTask updateTask;

    @PostConstruct
    public void init(){
        try {
            PortletPreferences portletPrefs = ((PortletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getPreferences();
            updateTask = new MyUpdateTask(portletPrefs);
            MyTaskService.getInstance().update(updateTask);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}

MyTaskService.update uses a ScheduledExecutorService that generates a service to regularly update my data.

the problem I have right now is that ((PortletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getPreferences(); throws an UnsupportedOperationException because there is currently no request. How can I get a PortletPreferences without a request?

I do need a PortletPreferences object for the task.

Upvotes: 1

Views: 552

Answers (1)

Neil Griffin
Neil Griffin

Reputation: 822

If you are using Liferay Portal, then...

During the RENDER_PHASE of the portlet lifecycle, Liferay Portal executes render_portlet.jsp (which sets up the PortletPreferences object for the RenderRequest). Lines 52-54 of render_portlet.jsp look like this:

PortletPreferencesIds portletPreferencesIds =
    PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portletId);
PortletPreferences portletPreferences =
    PortletPreferencesLocalServiceUtil.getStrictPreferences(portletPreferencesIds);

So I recommend that you call one of the overloaded PortletPreferencesFactoryUtil.getPortletPreferencesIds(...) methods that do not take a request object in order to retrieve the preferences associated with the portlet.

Since you don't have access to the PortletConfig you would need to hard-code the portletId as a String constant. If you need to get the portletId dynamically then instead of an @ApplicationScoped bean you could possibly @Override GenericFacesPortlet.init(PortletConfig) and start the TimerTask from there.

Otherwise, if not using Liferay Portal, then I am not aware of any part of the Portlet API that would let you get access to the PortletPreferences outside the context of a PortletRequest.

Upvotes: 3

Related Questions