Display content of JSP file in browser through Liferay Struts Action - liferay

How to display the content of jsp file in browser through Liferay Struts Action (DXP 7.1)? I use the execute method with parameters of HttpServletRequest and HtttpServletResponse, and place the jsp file in resources/META-INF/resources, but it is not showing in the browser, also no any errors in microservice logs.
The project, where I'm implementing new functionality, use Scala and SBT, so I can't use maven or something else.
I tried to follow the official documentation of overriding Liferay Struts action on their page, but it describe case for DXP 6.x version, despite this, I still tried the described approach using struts-config.xml, but it did not help.
The latest iteration of implementation based on of using requestDispatcher, but I'm not sure this is right:
class RedirectInfoAction extends BaseStrutsAction with LiferayLogSupport {
override def execute(
originalStrutsAction: StrutsAction,
request: HttpServletRequest,
response: HttpServletResponse
): String = {
log.info("Strut action execution started...")
getUserId(request) match {
case Some(_) =>
val servletContext = request.getSession().getServletContext
val requestDispatcher = servletContext.getRequestDispatcher("/page.jsp")
requestDispatcher.include(request, response)
case None =>
response.sendError(401, "The user is not authorized")
}
""
}

It all depends on how you deploy the code: You're just posting the code here, but if you look at the blade sample for a struts action, you'll see an additional critical part, which is the #Component section (granted, this requires using Java), as well as the #Reference to the servlet context.
You can also manually register such a service to the OSGi runtime, but that requires quite a lot of internal OSGi knowledge.
#Component(
immediate = true, property = "path=/portal/blade",
service = StrutsAction.class
)
public class BladeStrutsAction extends BaseStrutsAction {
public String execute(
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws Exception {
RequestDispatcher requestDispatcher =
_servletContext.getRequestDispatcher("/html/portal/blade.jsp");
requestDispatcher.forward(httpServletRequest, httpServletResponse);
return null;
}
#Reference(target = "(osgi.web.symbolicname=blade.strutsaction)")
private volatile ServletContext _servletContext;
}
(see the rest of the project as well: There's a bnd.bnd that contains information for the osgi.web.symbolicname configuration, etc)

Related

Spring Integration - Customize ObjectMapper used by WebFlux OutboundGateway

How do we customize the Jackson ObjectMapper used by WebFlux OutboundGateway? The normal customization done via Jackson2ObjectMapperBuilder or Jackson2ObjectMapperBuilderCustomizer is NOT respected.
Without this customization, LocalDate is serialized as SerializationFeature.WRITE_DATES_AS_TIMESTAMPS. Sample output - [2022-10-20] and there is NO way to customize the format
I assume you really talk about Spring Boot auto-configuration which is applied to the WebFlux instance. Consider to use an overloaded WebFlux.outboundGateway(String uri, WebClient webClient) to be able to auto-wire a WebClient.Builder which might be already configured with the mentioned customized ObjectMapper.
Registering a bean of type com.fasterxml.jackson.databind.module.SimpleModule will automatically be used by the pre-configured ObjectMapper bean. In SimpleModule, it is possible to register custom serialization and deserialization specifications.
To put that into code, a very simple solution would be the following:
#Bean
public SimpleModule odtModule() {
SimpleModule module = new SimpleModule();
JsonSerializer<LocalDate> serializer = new JsonSerializer<>() {
#Override
public void serialize(LocalDate odt, JsonGenerator jgen, SerializerProvider provider) throws IOException {
String formatted = odt.format(DateTimeFormatter.ISO_LOCAL_DATE);
jgen.writeString(formatted);
}
};
JsonDeserializer<LocalDate> deserializer = new JsonDeserializer<>() {
#Override
public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return LocalDate.parse(jsonParser.getValueAsString());
}
};
module.addSerializer(LocalDate.class, serializer);
module.addDeserializer(LocalDate.class, deserializer);
return module;
}
Note that using lambdas for the implementations has sometimes resulted in weird behaviors for me, so I tend not to do that.

How to put JSF message bundle outside of WAR so it can be edited without redeployment?

We have a JSF application on WildFly 8 which uses the traditionally mechanism with internationalizing text by having message bundles for German and English in the WEB-INF\classes folder of the WAR and a configuration in faces-config.xml mapping a name to it and listing the locales. The application does not have a database connection, but uses REST services to communicate with a 2nd application.
Now we need to be able to change text more easily, meaning not having to build a new WAR file and do a deployment when changing a text. So I need a mechanism to have the message bundles outside of the WAR while being able to use it as before within the XHTML pages.
Two optional requirements would be to change the text and refresh the messages in the application without having to restart the application (priority 2), and to have a default bundle within the WAR, which is overwritten by the external bundle (priority 3).
My thought was to use something like Apache commons configuration to read a property file within an Application scoped bean and expose a getter under the EL name used before. But somehow it feels like having to re-implement an existing mechanism and that this should somehow be easier, maybe even with Java EE core only.
Has someone used this mechanism in such a way and can point me to some example/description on the details or has a better idea to implement the listed requirement(s)?
How to put JSF message bundle outside of WAR?
Two ways:
Add its path to the runtime classpath of the server.
Create a custom ResourceBundle implementation with a Control.
change the text and refresh the messages in the application without having to restart the application
Changing the text will be trivial. However, refreshing is not trivial. Mojarra internally caches it agressively. This has to be taken into account in case you want to go for way 1. Arjan Tijms has posted a Mojarra specific trick to clear its internal resource bundle cache in this related question: How to reload resource bundle in web application?
If changing the text happens in the webapp itself, then you could simply perform the cache cleanup in the save method. If changing the text however can happen externally, then you'd need to register a file system watch service to listen on changes (tutorial here) and then either for way 1 clear the bundle cache, or for way 2 reload internally in handleGetObject().
have a default bundle within the WAR, which is overwritten by the external bundle
When loading them from classpath, the default behavior is the other way round (resources in WAR have higher classloading precedence), so this definitely scratches way 1 and leaves us with way 2.
Below is a kickoff example of way 2. This assumes that you're using property resource bundles with a base name of text (i.e. no package) and that the external path is located in /var/webapp/i18n.
public class YourBundle extends ResourceBundle {
protected static final Path EXTERNAL_PATH = Paths.get("/var/webapp/i18n");
protected static final String BASE_NAME = "text";
protected static final Control CONTROL = new YourControl();
private static final WatchKey watcher;
static {
try {
watcher = EXTERNAL_PATH.register(FileSystems.getDefault().newWatchService(), StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
private Path externalResource;
private Properties properties;
public YourBundle() {
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
setParent(ResourceBundle.getBundle(BASE_NAME, locale, CONTROL));
}
private YourBundle(Path externalResource, Properties properties) {
this.externalResource = externalResource;
this.properties = properties;
}
#Override
protected Object handleGetObject(String key) {
if (properties != null) {
if (!watcher.pollEvents().isEmpty()) { // TODO: this is naive, you'd better check resource name if you've multiple files in the folder and keep track of others.
synchronized(properties) {
try (InputStream input = new FileInputStream(externalResource.toFile())) {
properties.load(input);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
return properties.get(key);
}
return parent.getObject(key);
}
#Override
#SuppressWarnings({ "rawtypes", "unchecked" })
public Enumeration<String> getKeys() {
if (properties != null) {
Set keys = properties.keySet();
return Collections.enumeration(keys);
}
return parent.getKeys();
}
protected static class YourControl extends Control {
#Override
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
String resourceName = toResourceName(toBundleName(baseName, locale), "properties");
Path externalResource = EXTERNAL_PATH.resolve(resourceName);
Properties properties = new Properties();
try (InputStream input = loader.getResourceAsStream(resourceName)) {
properties.load(input); // Default (internal) bundle.
}
try (InputStream input = new FileInputStream(externalResource.toFile())) {
properties.load(input); // External bundle (will overwrite same keys).
}
return new YourBundle(externalResource, properties);
}
}
}
In order to get it to run, register as below in faces-config.xml.
<application>
<resource-bundle>
<base-name>com.example.YourBundle</base-name>
<var>i18n</var>
</resource-bundle>
</application>

Packaging Facelets (JSF 2.2) files in a JAR - Deployed as JBoss Modul (seperate deployment)

My Question is near the same than Packaging Facelets files (templates, includes, composites) in a JAR. Wich was full quallyfied awnsered by BalusC.
But I'll go a bit farther. Since JBoass AS 7 the ClassLoading in JB has changed. Now there is a strict Modul-ClassLoading and it works so far ;)
I have a WAR-file with an jboss-deployment-structure.xml plus one JAR-file with some CDI-Beans and xhtml-files in /META-INF/resources/modul.
I deploy the two "projects" seperately (so the JAR is not packaged into the WAR both ar copyed in JBOSS_HOME/standalone/deployment).
The WAR references the JAR as a Modul through the jboss-deployment-structure.xml.
I'm able to Inject CDI-Beans from the JAR but I can't reach the xhtml-files in /META-INF/resources/modul/. Everytime I try to load CONTEXT_ROOT/modul/modul.xhtml I get a warning from JB :
[javax.enterprise.resource.webcontainer.jsf.application] (default task-5) JSF1064: Ressource /modul/modul.xhtml can not be found or served.
If I package the JAR into the WAR (WEB-INF/lib) it dosen't work ither.
I provided a faces-config.xml under META-INF/resources
Did I miss somethink?
reggards
I use WildFly 9.0.1 Final and the Provided J2EE implementations.
I found a solution. The problem is, that JBoss doesn't scan the JAR if it is not packaged in WEB-INF/lib.
In my initial question I have wrote "If I package the JAR into the WAR (WEB-INF/lib) it doesn't work ither." thats not true i just didn't recognise that i placed my files in /META-INF/modul instead of /META-INF/resources/modul. I moved the files and it start to work if i placed the JAR in WEB-INF/lib.
But the problem with an separate deployment still persisted.
Now I use an custom ResourceHandler (JSF 2.2 way) and it work like a charm.
All my moduls have to implement a interface. In that way I'm able to Inject all these instances by CDI. Now i itterate over all moduls and look for my resource. The ResourceHandler is placed in the WAR not in the single JAR's. In that way i just have to implement it onetimes.
Here is my code example:
public class ExternalResourceHandler extends ResourceHandler {
#Inject
#Any
Instance<ModulDescriptor> moduls;
private ResourceHandler parent;
private String basePath = "META-INF/resources";
public ExternalResourceHandler() {
}
public ExternalResourceHandler(ResourceHandler parent) {
this.parent = parent;
}
#Override
public ViewResource createViewResource(FacesContext context, String resourceName) {
System.out.println("Invoked for: " + resourceName);
ViewResource resource = parent.createViewResource(context, resourceName);
if (resource == null) {
System.out.println("Parent failed");
if (moduls != null) {
for (ModulDescriptor mod : moduls) {
URL url = mod.getClass().getClassLoader().getResource(basePath + resourceName);
if (url != null) {
return new ViewResource() {
#Override
public URL getURL() {
return url;
}
};
}
}
} else {
System.out.println("INJECTION IS NULL");
}
}
return resource;
}
//followed by all other overriden methods wich return null ;)
}
Thanks to #BalusC for this awnser wich does the clue in the second step.

Using liferay dockbar notifications

I’d like to use the liferay notification feature following the tutorial http://www.codeyouneed.com/liferay-custom-notifications/. And as many people before, I succeeded in increasing the number of notifications, but the notification message is not displayed.
I tried to check by adding log-output whether the methods (getBody, getLink, …) of the UserNotificationHandler are called, and they are not called at all, not even the constructor of the UserNotificationHandler is called.
So I conclude that my notification is written to the database, but my UserNotificationHandler class is not found.
In my project, I have put the
user-notification-definitions into
project/src/main/resources.
They look like:
<?xml version="1.0"?>
<!DOCTYPE user-notification-definitions PUBLIC "-//Liferay//DTD User Notification Definitions 6.2.0//EN" "http://www.liferay.com/dtd/liferay-user-notification-definitions_6_2_0.dtd">
<user-notification-definitions>
<definition>
<notification-type>${com.myproject.portal.notifications.UserNotificationHandler.PORTLET_ID}</notification-type>
<description>receive-a-notification-when-triggered</description>
<delivery-type>
<name>email</name>
<type>${com.liferay.portal.model.UserNotificationDeliveryConstants.TYPE_EMAIL}</type>
<default>true</default>
<modifiable>true</modifiable>
</delivery-type>
<delivery-type>
<name>website</name>
<type>${com.liferay.portal.model.UserNotificationDeliveryConstants.TYPE_WEBSITE}</type>
<default>true</default>
<modifiable>true</modifiable>
</delivery-type>
</definition>
</user-notification-definitions>
The liferay-portlet.xml is in
project/src/main/webapp/WEB-INF.
And the UserNotificationHandler in
project/src/main/java/com/myproject/portal/notifications
in the package com.myproject.portal.notifications.
I wrote something like that into the liferay-portlet.xml:
<portlet-name>example</portlet-name>
<icon>/icon.png</icon>
<user-notification-definitions>
user-notification-definitions.xml
</user-notification-definitions>
<user-notification-handler-class>
com.myproject.portal.notifications.UserNotificationHandler
</user-notification-handler-class>
</portlet>
This is my UserNotificationHandlerClass (so far, I am just trying to get it work before adding the actual content):
package com.myproject.portal.notifications;
import ...//all necessary imports
public class UserNotificationHandler extends
BaseUserNotificationHandler {
public static final String PORTLET_ID = "example_WAR_myprojectportlet";
private static final Logger log = Logger.getLogger(UserNotificationHandler.class);
public UserNotificationHandler() {
log.info("UserNotificationHandler - Constructor");
setPortletId(UserNotificationHandler.PORTLET_ID);
}
#Override
protected String getBody(UserNotificationEvent userNotificationEvent,
ServiceContext serviceContext) throws Exception {
log.info("in getBody");
return "";
}
#Override
protected String getLink(UserNotificationEvent userNotificationEvent,
ServiceContext serviceContext) throws Exception {
log.info("in getLink");
return "";
}
protected String getBodyTemplate() throws Exception {
log.info("in getBodyTemplate");
return "";
}
}
I trigger the notification in my portlet like this:
ServiceContext serviceContext = ServiceContextFactory.getInstance(request);
JSONObject payloadJSON = JSONFactoryUtil.createJSONObject();
payloadJSON.put("userId", userId);
payloadJSON.put("yourCustomEntityId", 12345);
payloadJSON.put("additionalData", "success");
UserNotificationEventLocalServiceUtil.addUserNotificationEvent(userId,
UserNotificationHandler.PORTLET_ID,
(new Date()).getTime(),
userId,
payloadJSON.toString(),
false,
serviceContext);
What is the problem here?
Do you literally have public static final String PORTLET_ID = "myportlet"; in your code? If so, note the extra information in the tutorial that you link:
NB Important Information: The com.example.notifications.ExampleUserNotificationHandler.PORTLET_ID string that you use as your notification type has to match an actual portlet ID. It doesn’t actually need to be YOUR portlet ID but that would be the right thing to have there. The reason being that Notifications display portlet uses it to display a small portlet icon next to your notification to help the user identify the source of the notification. Providing a bad Portlet ID or something like null leads to a hard-to-trace NullPointerException in the JSP. Took me an hour to track it down.
Most likely the portlet ID looks rather like "example_WAR_myportlet", this indicates that it's deployed in a plugin named example.war and the portlet id (in portlet.xml) is myportlet. Try if it works then - Liferay might need to find the portlet in order to find, instanciate and use its NotificationHandler. (Note: This is currently a guess - I didn't try the full code posted)
In your liferay-portlet.xml you wrote
<user-notification-handler-class>
UserNotificationHandler
</user-notification-handler-class>
It should be:
<user-notification-handler-class>
com.myproject.portal.notifications.UserNotificationHandler
</user-notification-handler-class>
You should also check if this part is good
<user-notification-definitions>
user-notification-definitions.xml
</user-notification-definitions>
"user-notification-definitions.xml" file should be on WEB-INF/classes in the final WAR

How to handle HTTP 403 with Spring Security 3.0.x

I'm facing a little issue with Spring Security 3.0.x (3.0.2 in particular at the moment). The whole application I'm working on is working perfectly except when someone who doesn't have the authorities tries to log on.
When it occurs, the users is redirected to the "welcome" page, since his username/password are valid, and he receive a cute white page with this : "Error 403: Access is denied"
So, I've been looking on the net trying to find how this behavior can be handled. So far I've come to the conclusion, please correct me if I'm wrong, that it is managed by the ExceptionTranslationFilter. But I don't quite understand how to make any good use of this information.
I've tryied to edit my SecurityContext.xml to add a access-denied-handler tag to my http tag, but it doesn't work. Do I need to add more than this tag to make it work? Is there any other possibilities to make my application more user-friendly?
Edit : I would like to redirect to a page, let's says 403.html, for example.
Sincerly,
Thanks
I still don't get why you had to implement your own access handler... I have currently faced same task:
<security:access-denied-handler error-page="/accessDenied"/> - works like charm.
Don't forget to specify handler in your Controller:
#RequestMapping(value = "/accessDenied")
public String accessDenied() {
return "accessDenied"; // logical view name
}
Update for Spring Boot(2014 Oct):
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(customHandler) OR .accessDeniedPage("/somePage.html").and
.formLogin()
.failureHandler(ajaxAuthenticationFailureHandler)}
Nowadays we don't really return views for such task since angular js kicks in so you can use your failure/success handler and return tailored JSON responses. For us it was sufficient to use failure handler but you get to choose where you want your control to kick in. We generally don't use view resolvers as there are UI tiles frameworks(such as angular partials) able to construct pieces into single page for you. Html pieces are stored on the server and served simply as static resources.
Lets play with Embedded Tomcat to achieve similar behavior to web.xml !
#Configuration
#EnableAutoConfiguration
public class ApplicationWebXml extends SpringBootServletInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.profiles(addDefaultProfile())
.showBanner(false)
.sources(Application.class);
}
//required for container customizer to work, the numerous tutorials didn't work for me, so I simply tried overriding the default one
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
return tomcat;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer(
) {
return new EmbeddedServletContainerCustomizer() {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
containerFactory.setSessionTimeout(1); // just for your interest, remove as necessary
containerFactory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN,"/views/accessDenied.html"),
new ErrorPage(HttpStatus.NOT_FOUND,"/views/notFound.html"));
containerFactory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
#Override
public void customize(Connector connector) {
connector.setPort(8082);// just for your interest, remove as necessary
}
});
}
};
}
}
A cleaner way to handle error redirects is to use the <error-page> and <error-code> tags in your web.xml. See below for an example:
<!-- Custom 403 Error Page -->
<!--
NOTE: Security will throw this error when a user has been authenticated successfully
but lacks the permissions to perform the requested action.
-->
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
This block of code will redirect to the specified location whenever it encounters the specified error code.
This eliminates the need for authorization code inside your application logic.
I've found how to do this. By implementing the AccessDeniedHandler interface and the corresponding handle method I can, easily, control the way the Http 403 error is handled.
This way, you can add various items in the session and then intercept them on your jsp.
The xml file then looks like this :
<sec:http>
<!-- lots of urls here -->
<sec:access-denied-handler ref="accessDeniedHandler" />
<sec:anonymous/>
</sec:http>
<bean id="accessDeniedHandler" class="foo.bar.CustomAccessDeniedHandler">
<property name="accessDeniedUrl" value="403.html" />
</bean>
The java class :
package foo.bar;
public class CustomAccessDeniedHandler implements org.springframework.security.web.access.AccessDeniedHandler {
private String accessDeniedUrl;
public CustomAccessDeniedHandler() {
}
public CustomAccessDeniedHandler(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect(accessDeniedUrl);
request.getSession().setAttribute("CustomSessionAttribute", "value here");
}
public String getAccessDeniedUrl() {
return accessDeniedUrl;
}
public void setAccessDeniedUrl(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
}
And a jsp example :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${!empty CustomSessionAttribute}">
<br/>
ACCESS IS DENIED
<br/>
</c:if>
<!-- other stuff down here -->
The way to make this work is to define a handler in your entry point:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException {
if (authException != null) {
// you can check for the spefic exception here and redirect like this
response.sendRedirect("403.html");
}
}
}
You can define this as your entry point by setting this as you entry point in the xml config file:
<http entry-point-ref="customAuthenticationEntryPoint">
...
</http>
You have checked the tag in an application and to me it seems to work.
<sec:access-denied-handler error-page="/handle403Url" />
where handle403Url I want to call to handle this error (for example to show an error).
Don't forget that you have to allow this url in the filters so it can be reached by this user authority, so in the start of the flters you have to add something like this:
<sec:intercept-url pattern="/handle403Url" filters="none" />

Resources