Is there a way to log the requests coming for static files (like index.html or js files) in JHipster.
Add a filter:
public class RequestLoggingFilter implements Filter {
private static final Logger log = Logger.getLogger(AuditFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestUrl = httpRequest.getRequestURI();
String requestMethod = httpRequest.getMethod();
log.info("Received " + requestMethod + " request + " for " + requestUrl);
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}
Related
I have a ThreadLocale in which i am setting some value which i want to read while creating the mongo document..
#Service
public class DocumentContext {
private ThreadLocal<String> currentValue = new ThreadLocal<>();
public void setName(String documentName) {
currentValue.set(documentName);
}
public String getName() {
return currentValue.get();
}
}
I am using this to set the value in my filter:
#Autowired
private DocumentContext docContext;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final String col= "value1";
docContext.setCurrentValue(col);
chain.doFilter(request, response);
docContext.setCurrentValue(null);
}
Now i have my POJO class in which i am using like this:
#Data
#Document(collection="doc.#{docContext.getName()}.tableName")
class Entity{
}
But, in the mongo i am getting the collection name as :
doc..tablename
I was expecting :
doc.value1.tablename
Please suggest am i missing something.
I've tried to make autorisation form by using jsf 1.2 but I had some exceptions with redirect.
Bean code
public class UserAutorisationBean implements Serializable {
private Boolean isLogin = false;
private String login = "";
private String password = "";
public void autoriseLoginAndPass() throws IOException {
if (this.login == "user" && this.password == "password") {
this.isLogin = true;
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/HelloWorld.jsp");
} else {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/Error.jsp");
}
}
Filter code
public class Filter implements javax.servlet.Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = null;
session = httpRequest.getSession(false);
if (session != null) {
UserAutorisationBean userAutorisationBean = null;
userAutorisationBean =
(UserAutorisationBean) session.getAttribute("userautorisationbean");
if (userAutorisationBean != null) {
if (!userAutorisationBean.isLoginIn()) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
chain.doFilter(request, response);
}
if (session == null) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
public void destroy() {
}
}
Stack:
message Cannot forward after response has been committed
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Cannot forward after response has been committed
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
root cause
java.lang.IllegalStateException: Cannot forward after response has been committed
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:414)
com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:455)
com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:139)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:266)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:159)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
I've tried to find some advices by using search but it didn't help me to solve the problem.
As I have an Apache Webserver which does ProxyPass to the Glassfish server, the latter does not know that the customers are talking "https".
Thus when using things like
return "shop.xhtml?faces-redirect=true";
the generated HTTP Location: header contains a "http://" URL.
I've read JSF redirects from HTTPS to HTTP but found this solution not very elegant. Is there a way to tell Glassfish that this or all incoming requests are https so that I don't have to fiddle with the generated Navigation rules?
You may try to add some request header which can be interpreted on java side, for example 'X-redirect-to-https'. Then create filter that will wrap HttpServletResponse, and in that wrapper override sendRedirect method to replace http with https in redirect URL when 'X-redirect-to-https' header is present.
Code (a little messy, but illustrates a solution) adapted from:
http://javahunter.wordpress.com/2011/06/01/why-does-https-become-http-on-a-sendredirect/
#WebFilter("/*")
public class HttpsSendRedirectFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
chain.doFilter(request, new HttpsRedirectResponseWrapper((HttpServletRequest) request,
(HttpServletResponse) response));
}
}
public class HttpsRedirectResponseWrapper extends HttpServletResponseWrapper {
private HttpServletRequest req;
private String prefix = null;
public HttpsRedirectResponseWrapper(HttpServletRequest req, HttpServletResponse res) {
super(res);
this.req = req;
prefix = getPrefix(req);
}
#Override
public void sendRedirect(String location) throws IOException {
String finalurl = null;
if (isUrlAbsolute(location)) {
finalurl = location;
} else {
finalurl = fixForScheme(prefix + location);
}
super.sendRedirect(finalurl);
}
public boolean isUrlAbsolute(String url) {
String lowercaseurl = url.toLowerCase();
if (lowercaseurl.startsWith("http") == true) {
return true;
} else {
return false;
}
}
public String fixForScheme(String url) {
if (this.req.getHeader("X-redirect-to-https") != null) {
return url.replaceFirst("http", "https");
} else {
return url;
}
}
public String getPrefix(HttpServletRequest request) {
StringBuffer str = request.getRequestURL();
String url = str.toString();
String uri = request.getRequestURI();
int offset = url.indexOf(uri);
String prefix_t = url.substring(0, offset);
return prefix_t;
}
}
#WebFilter(filterName = "loginFilter", value = { "/faces/kosz.xhtml" } , dispatcherTypes = { DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE } )
public class loginFilter implements Filter {
public loginFilter(){
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException{
HttpServletRequest req = ( HttpServletRequest ) request;
userSession auth = ( userSession ) req.getSession().getAttribute("user");
if ( auth != null && auth.isLogged() ) {
chain.doFilter(request, response);
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
else {
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void destroy()
{
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Return the filter configuration object for this filter.
}
The problem is that the filter doesn't execute. THe URL is localhost:8080/PP2/faces/kosz.xhtml . What would be the proper way to do this?
I have no entry in my web.xml, it's all based on Annotations.
You throw exceptions in init() and destroy() methods of filter. If you don't want to do anything in init() or destroy(), just leave body of method empty. In this case your filter is not successfully initialized at all.
I'm getting a ViewExpiredException when I'm at my login page, it is not supposed to be. So I read a post (recommended by BalusC) on Filters. It might be that the page is loading from browser's cache and not from server. So I've implemented this code
#WebFilter(servletNames={"Faces Servlet"})
public class NoCacheFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
if (!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
httpRes.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
httpRes.setHeader("Pragma", "no-cache"); // HTTP 1.0.
httpRes.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
// ...
#Override
public void init(FilterConfig filterConfig) throws ServletException {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void destroy() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
but when I try to test it I get the following error:
The module has not been deployed.
at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:210)
at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:106)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
at sun.reflect.GeneratedMethodAccessor193.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:390)
at org.apache.tools.ant.Target.performTasks(Target.java:411)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:284)
at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:539)
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
You're throwing an exception during filter's initialization (and destroy). So filter's initialization will completely fail and cause the webapp's startup to be blocked. Remove those lines. You shouldn't purposefully throw an exception in there.
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// NOOP.
}
#Override
public void destroy() {
// NOOP.
}
Read the filter's javadoc to learn about what those methods are for.
See also:
Our Servlet-Filters tag wiki page