I am trying to get liferay userId (I am using primefaces 6.2 in Liferay 7).
What I have tried so far is:
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
long userId = td.getUserId();
I am getting the below error:
ERROR [stderr] (default task-49) java.lang.ClassCastException: com.liferay.faces.bridge.ext.filter.internal.ResourceRequestBridgeLiferayImpl cannot be cast to javax.servlet.http.HttpServletRequest
I have searched the problem, but not able to find out a working solution. Any help would be highly appreciated.
Thanks in advance.
I also tried using PortletRequest. Below is the code.
PortletRequest request = (PortletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
ThemeDisplay td =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
But now ThemeDisplacy class is not found
java.lang.NoClassDefFoundError: com/liferay/portal/theme/ThemeDisplay: javax.el.ELException: java.lang.NoClassDefFoundError: com/liferay/portal/theme/ThemeDisplay
I am not sure where i am missing.
Thanks
To fetch the Liferay User object, you could use the following snippet:
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
User u = PortalUtil.getUser(portletRequest);
Please also read this article about the return value of ExternalContext.getRequest() - this might be the reason of your cast error.
The article further explains that: "the ExternalContext.getRequest() method returns an Object instead of an javax.servlet.http.HttpServletRequest. When this method is used in a portal, the Object can be cast to a javax.portlet.PortletRequest."
Related
I would like to be able to retrieve a string from a message bundle from inside a JSF 2 managed bean. This would be done in situations where the string is used as the summary or details parameter in a FacesMessage or as the message in a thrown exception.
I want to make sure that the managed bean loads the correct message bundle for the user's locale. It is not clear to me how to do this from a managed bean using JSF API calls.
My configuration is:
Using Tomcat 7 as the container so the solution cannot depend on API calls that only work in a full application server container
Using the JSF 2 reference implementation (Mojarra)
NOT using any libraries that allow CDI
NOTE: I did see this similar question, but it depends on features that are unavailable in my configuration
EDIT: I made a mistake in my original question. What I meant to ask was "How can I get a resource bundle string from inside a managed bean"? BalusC gave me the correct answer for what I asked. The solution for what I actually meant to ask is very similar:
public static String getResourceBundleString(
String resourceBundleName,
String resourceBundleKey)
throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ResourceBundle bundle =
facesContext.getApplication().getResourceBundle(
facesContext, resourceBundleName);
return bundle.getString(resourceBundleKey);
}
Also, here is a link to another question that explains the difference between "message" bundles and "resource" bundles.
You can get the full qualified bundle name of <message-bundle> by Application#getMessageBundle(). You can get the current locale by UIViewRoot#getLocale(). You can get a ResourceBundle out of a full qualified bundle
name and the locale by ResourceBundle#getBundle().
So, summarized:
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
Locale locale = facesContext.getViewRoot().getLocale();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, locale);
// ...
Update: as per the mistake in the question, you actually want to get the bundle which is identified by the <base-name> of <resource-bundle>. This is unfortunately not directly available by a standard JSF API. You've either to hardcode the same base name in the code and substitute the messageBundleName in the above example with it, or to inject it as a managed property on <var> in a request scoped bean:
#ManagedProperty("#{msg}")
private ResourceBundle bundle; // +setter
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");
String message = bundle.getString("key");
here is key is property name which you want to access from properties file .
message = This is "message"
This entry is from messages.properites file. and "message" is "key" .
There are two ways to get String resource bundle in managed bean, using baseName or varName (see definition of each one below):
Using varName:
varName: is the String representing the <var></var> in <resource-bundle>
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ResourceBundle bundle = app.getResourceBundle(context, varName);
String msg = bundle.getString("key");
Using baseName:
baseName: The fully qualified name of the resource bundle (<base-name> in <resource-bundle>).
FacesContext context = FacesContext.getCurrentInstance();
Locale locale = context .getViewRoot().getLocale();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader);
String msg = bundle.getString("key");
i got this problem when i try to export a datatable information to PDF, the method do all, but it doesn't download the PDF or even generate.
Netbeans version: 8.2
JSF: 2.2
Primefaces: 5.3
Libraries used:
Jasperreports 6.3
poi 3.14
commons-beanutils-1.9.0
commons-collection-3.2.2
commons-digester-2.1
commons-logging-1.1.1
groovy-all-2.4.0
itext-2.1.7.js5
jaxp-ri
jcommon-1.0.23
jfreechart-1.0.19
And my method is:
public void exportpdf(OrdenRetiro or) throws JRException, IOException {
conexion con = new conexion();
Map<String, Object> parametros = new HashMap<String, Object>();
FacesContext context = FacesContext.getCurrentInstance();
ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
parametros.put("cod_ordenretiro", or.getCod_ordenretiro());
String temperatura = or.getEs_temperado()==1?"ReporteFreezer.jasper":"ReporteNoFreezer.jasper";
String dirReporte = servleContext.getRealPath("/reportes/"+temperatura);
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.addHeader("Content-disposition", "attachment;filename=Orden de Retiro"+or.getCod_ordenretiro()+".pdf");
response.setContentType("application/pdf");
JasperPrint impres = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
JasperExportManager.exportReportToPdfStream(impres, response.getOutputStream());
context.responseComplete();
}
Any idea?
Got the solution.
When the method works but doesn't export is because the ajax on the xhtml. After doing some research got the answer here
I make the puntual quote.
The first problem is that the <p:commandLink> sends by default an Ajax
request. This request is fired by JavaScript code. However, JavaScript
can't do anything with a response which contains a file download. Due
to security restrictions JavaScript can't spawn a Save As dialogue or
something. The response is basically totally ignored.
You need to add ajax="false" to <p:commandLink> to turn ajax off so
that the button fires a normal synchronous HTTP request, or you need
to replace it by standard <h:commandButton>
In a JSF backing bean (Managed Bean, Weld Bean, doesn't matter), I can get the context path the client is on by calling
FacesContext ctx = FacesContext.getCurrentInstance();
String path = ctx.getExternalContext().getRequestContextPath();
This gives me the path the client currently accesses, like /myapplication.
Is it also possible to get the current page, like /home.faces, and how?
You normally want to use UIViewRoot#getViewId() for this.
String viewId = facesContext.getViewRoot().getViewId();
This is in EL also available as follows:
#{view.viewId}
Exactly this value is reuseable in navigation case outcomes such as <h:link outcome> and <h:button outcome>.
Alternatively, you can also use HttpServletRequest#getRequestURI() to get whatever the enduser is actually seeing in the browser address bar.
String uri = ((HttpServletRequest) externalContext.getRequest()).getRequestURI();
Which is in EL also available as follows:
#{request.requestURI}
Exactly this value is reuseable in <h:outputLink value> or plain <a href>. Note that you can't use it as navigation case outcome.
Ok, got it, it's
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest servletRequest = (HttpServletRequest) ctx.getExternalContext().getRequest();
// returns something like "/myapplication/home.faces"
String fullURI = servletRequest.getRequestURI();
String uri = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURI();
String str = ((HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest()).getRequestURI();
System.out.println(str);
In Vaadin 6,
you could override onRequestStart to obtain the PortletRequest object like so
#Override
public void onRequestStart(PortletRequest request, PortletResponse response)
In Vaadin 7, due to the portlet class change to com.vaadin.server.VaadinPortlet, there is no more onRequestStart to get the PortletReqeust object, just their new VaadinRequest object.
#Override
protected void init(VaadinRequest request)
Issue is getting this to a PortletRequest to be used. Anyone found a way to retrieve PortletRequest from Vaadin 7 and liferay?
Once you find the information that a VaadinRequest is both VaadinPortletRequest and VaadinServletRequest, you can retrieve PortletRequest and HttpServletRequest as so:
VaadinPortletRequest vprRequest = (VaadinPortletRequest) request;
PortletRequest pRequest = vprRequest.getPortletRequest();
VaadinServletRequest vsRequest = (VaadinServletRequest)request;
HttpServletRequest hsRequest = vsRequest.getHttpServletRequest();
This will do as well
PortletRequest currentPortlet = VaadinPortletService.getCurrentPortletRequest();
I would like to be able to retrieve a string from a message bundle from inside a JSF 2 managed bean. This would be done in situations where the string is used as the summary or details parameter in a FacesMessage or as the message in a thrown exception.
I want to make sure that the managed bean loads the correct message bundle for the user's locale. It is not clear to me how to do this from a managed bean using JSF API calls.
My configuration is:
Using Tomcat 7 as the container so the solution cannot depend on API calls that only work in a full application server container
Using the JSF 2 reference implementation (Mojarra)
NOT using any libraries that allow CDI
NOTE: I did see this similar question, but it depends on features that are unavailable in my configuration
EDIT: I made a mistake in my original question. What I meant to ask was "How can I get a resource bundle string from inside a managed bean"? BalusC gave me the correct answer for what I asked. The solution for what I actually meant to ask is very similar:
public static String getResourceBundleString(
String resourceBundleName,
String resourceBundleKey)
throws MissingResourceException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ResourceBundle bundle =
facesContext.getApplication().getResourceBundle(
facesContext, resourceBundleName);
return bundle.getString(resourceBundleKey);
}
Also, here is a link to another question that explains the difference between "message" bundles and "resource" bundles.
You can get the full qualified bundle name of <message-bundle> by Application#getMessageBundle(). You can get the current locale by UIViewRoot#getLocale(). You can get a ResourceBundle out of a full qualified bundle
name and the locale by ResourceBundle#getBundle().
So, summarized:
FacesContext facesContext = FacesContext.getCurrentInstance();
String messageBundleName = facesContext.getApplication().getMessageBundle();
Locale locale = facesContext.getViewRoot().getLocale();
ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, locale);
// ...
Update: as per the mistake in the question, you actually want to get the bundle which is identified by the <base-name> of <resource-bundle>. This is unfortunately not directly available by a standard JSF API. You've either to hardcode the same base name in the code and substitute the messageBundleName in the above example with it, or to inject it as a managed property on <var> in a request scoped bean:
#ManagedProperty("#{msg}")
private ResourceBundle bundle; // +setter
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");
String message = bundle.getString("key");
here is key is property name which you want to access from properties file .
message = This is "message"
This entry is from messages.properites file. and "message" is "key" .
There are two ways to get String resource bundle in managed bean, using baseName or varName (see definition of each one below):
Using varName:
varName: is the String representing the <var></var> in <resource-bundle>
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
ResourceBundle bundle = app.getResourceBundle(context, varName);
String msg = bundle.getString("key");
Using baseName:
baseName: The fully qualified name of the resource bundle (<base-name> in <resource-bundle>).
FacesContext context = FacesContext.getCurrentInstance();
Locale locale = context .getViewRoot().getLocale();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader);
String msg = bundle.getString("key");