FacesMessages in MyFacesServlet Wrapper - java

I throw NullPointerException in a java bean and catch the exception in FacesServletWrapper.
in FacesServletWrapper I gets always only ServletException.
how can I catch the specific exception that I throw?
How can I continue from where I throws the exception?
in my bean:
public String getSize() {
try {
Object object = null;
object.equals("");
} catch (Exception e) {
throw new NullPointerException();
}
}
my servlet:
public class FacesServletWrapper extends MyFacesServlet {
public static final String CONFIG_FILES_ATTR = "javax.faces.CONFIG_FILES";
public static final String LIFECYCLE_ID_ATTR = "javax.faces.LIFECYCLE_ID";
private ServletConfig servletConfig;
private FacesContextFactory facesContextFactory;
private Lifecycle lifecycle;
#Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
FacesContext facesContext = facesContextFactory.getFacesContext(servletConfig.getServletContext(), request, response, (javax.faces.lifecycle.Lifecycle) lifecycle);
try {
super.service(request, response);
} catch (Throwable e) {
Locale locale = (Locale) facesContext.getExternalContext().getSessionMap().get(Constants.LOCALE);
ServletContext context = servletConfig.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/errors/error.jsf");
if (e instanceof NullPointerException) {
//here I catch only ServletException
String error = ResourceUtil.getMessage("Login_failed", locale);
facesContext.getExternalContext().getSessionMap().put("error", error);
dispatcher.forward(request, response);
((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/errors/error.jsf");
}
}
}
public void destroy() {
servletConfig = null;
facesContextFactory = null;
lifecycle = null;
}
public ServletConfig getServletConfig() {
return servletConfig;
}
private String getLifecycleId() {
String lifecycleId = servletConfig.getServletContext().getInitParameter(LIFECYCLE_ID_ATTR);
return lifecycleId != null ? lifecycleId : LifecycleFactory.DEFAULT_LIFECYCLE;
}
#Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
this.servletConfig = servletConfig;
facesContextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
lifecycle = (Lifecycle) lifecycleFactory.getLifecycle(getLifecycleId());
}
}
Thanks!

You're calling FacesServlet#service() here:
try {
super.service(request, response);
} catch (Throwable e) {
// ...
}
Here's an extract from its javadoc to learn what kind of exception it may throw:
If a FacesException is thrown in either case, extract the cause from the FacesException. If the cause is null extract the message from the FacesException, put it inside of a new ServletException instance, and pass the FacesException instance as the root cause, then rethrow the ServletException instance. If the cause is an instance of ServletException, rethrow the cause. If the cause is an instance of IOException, rethrow the cause. Otherwise, create a new ServletException instance, passing the message from the cause, as the first argument, and the cause itself as the second argument.
In other words, it will always throw either ServletException or IOException. You need to use Throwable#getCause() to extract the desired cause from the catched ServletException and then determine it further. E.g.
if (e.getCause() instanceof NullPointerException) {
// ...
}

Related

Pass an object from API resource Method to APIFilter PostCheckMethod

I have a use case in that for all PUT/Delete/Update call i want to send some object to PostCheck of ApiFilter for some processing.
I am trying like this :
#Context
HttpServletRequest request;
#Context
ContainerResponseContext responseContext ;
#PUT
#Path("/snmp")
#Produces(MediaType.APPLICATION_JSON)
#Timed
public Response<List<SNMPSettingsFactory.ExternalSNMPSettings>> updateSNMPTargetSettingsList(
#Nonnull SNMPSettingsFactory.ExternalSNMPSettings externalSNMPSettings)
{
request.setAttribute("old",oldSettingObject);
request.setAttribute("new",currentSettingObject);
}
in the ApiFilter class, I am trying to get this but it is coming as NULL.
#Provider
public class ApiFilter implements ContainerRequestFilter,
ContainerResponseFilter {
private final ApiNonFunctionalHandler handler;
private final Logger logger = LoggerFactory.getLogger(ApiFilter.class);
public ApiFilter(ApiNonFunctionalHandler handler) {
this.handler = handler;
}
#Context
HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
try {
String urlPath = requestContext.getUriInfo().getRequestUri().getPath();
if (!urlPath.startsWith(ApiConstants.BASE_URL)) {
return;
}
UserInfo userInfo;
String authorization = NullOrEmpty.isFalse(requestContext.getHeaderString(CspClient.AUTH_TOKEN_HEADER))?
requestContext.getHeaderString(CspClient.AUTH_TOKEN_HEADER) : requestContext.getHeaderString("Authorization");
userInfo = handler.preCheck(ApiUtils.getApiCategory(urlPath),
authorization, isAuthRequired(urlPath, requestContext.getMethod()));
requestContext.setSecurityContext(new CustomSecurityContext(userInfo,""));
} catch (RuntimeException e) {
throw Throwables.propagate(e);
} catch (Exception e) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws
IOException {
String urlPath = requestContext.getUriInfo().getRequestUri().getPath();
String callerIpAddress = null;
if (request != null) {
callerIpAddress = request.getRemoteAddr();
}
String callerUserName = null;
if (request != null) {
callerUserName = request.getRemoteUser();
}
Object oldObject = request.getAttribute("old");
Object currentObject = request.getAttribute("new");
Please help me how can I pass objects for all API call to postfilter to do some common processing like finding diff and log it.

how to redirect user for accessing to a page from URL in java?

I am coming to a problem where I have loginFilter where I dont want the user to access a page when they are logged in with the URL. So, all I want to do is redirect the user to the index page. Here is my code below. Thank you.
public class LoginFilter implements Filter {
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
String username = req.getHeader("username");
String password = req.getHeader("password");
if(username == null) {
chain.doFilter(request, response);
return;
}
try {
req.login(username, password);
chain.doFilter(request, response);
} catch (ServletException e) {
((HttpServletResponse)response).setStatus(StatusCodes.UNAUTHORIZED);
}
}
#Override
public void destroy() {
}
}
Change your method as :
HttpServletResponse res = (HttpServletResponse)response;
try {
req.login(username, password);
res.sendRedirect("/index");
} catch (ServletException e) {
// you can use SC_UNAUTHORIZED(401) from HttpServletResponse class as well
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}

How to catch already caught exception?

I have the follow the following filter:
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
try {
chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
} catch (XssAttackException e) {
request.getRequestDispatcher("/XssAttack").forward(request, response);
}
}
and the class XssAttackException is:
public class XssAttackException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
after debugging the code, I realized that somewhere in the spring framework all the exceptions are being caught. Now I need a way that my catch bock also run.
UPDATE
inside XSSRequestWrapper we have:
#Override
public String getHeader(String name) {
String value = super.getHeader(name);
return stripXSS(value);
}
And
private String stripXSS(String value) {
if (value != null) {
value = persianUtf8(value);
if (!value.equals(Jsoup.parse(value).text())) {
throw new XssAttackException();
}
value = Jsoup.parse(value).text();
for (Pattern scriptPattern : patterns) {
if (scriptPattern.matcher(value).matches()) {
throw new XssAttackException();
}
value = scriptPattern.matcher(value).replaceAll("");
}
}
return value;
}
Please don't assume this is answer for your question.Assumed too long comment.
I created my CustomException class.
public class CustomException extends RuntimeException {
}
and created custom Servlet class as your XSSRequestWrapper and throw my custom exception in constructor.
public class MyServlet implements ServletRequest {
public MyServlet() {
throw new CustomException();
}
// other override methods go here
}
and in my filter class
try {
chain.doFilter(new MyServlet(), response);
} catch (CustomException e) {
System.out.println("xxxxxxxxxxxxxxx I got it xxxxxxxxxxxxxxxxxxx");
}
This code work fine. At your program , I think there has some exception has occured and you did not catch on them. So , this exception object has miss from your try block of your filter class and handled by Spring container.

Is it clean code to return in a catch block?

I have a java servlet which checks for URL parameters (last uri part, wildcard). Given these parameters, I want to respond with a 404 or an actual response. Is it clean code to do a return; in the catch block?
#WebServlet("/processes/edit/*")
public class ProcessEditServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
try {
id = StringManipulation.removeSlashes(request.getPathInfo());
numid = Integer.parseInt(id);
} catch (NumberFormatException e) {
response.sendError(404);
return;
}
request.getRequestDispatcher("/WEB-INF/processEdit.jsp").forward(
request, response);
}
}
as dognose say, its much about the personal feeling. I would refactor this code as following:
#WebServlet("/processes/edit/*")
public class ProcessEditServlet extends HttpServlet {
// you may get a logger over Dependency Injection or joust create one here...
private final Logger logger;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
if(validateRequest(request,logger){
request.getRequestDispatcher("/WEB-INF/processEdit.jsp").forward(
request, response);
}else{
response.sendError(404);
}
}
public static boolean validateRequest(Request request,Logger logger){
try {
id = StringManipulation.removeSlashes(request.getPathInfo());
numid = Integer.parseInt(id);
} catch (Exception e) {
logger.log(e); // you should at least log the exception
return false;
}
return true;
}
}
Because, its testabler, and the whole try/catch-block bloat the code and made it less readable - i know peoples encapsulating each try and catch in its own method. However, cleancode means maintainable and readable code - in my opinion its ok when you return in a catch, as long as it makes sense.
Edit1: added logger
I'm pretty sure that if you actually catch an exception here, your return statement is going to cause this line of code:
request.getRequestDispatcher("/WEB-INF/processEdit.jsp").forward(
request, response);
not to execute. If you omit the return statement, it will execute even if an exception is caught.
This is what I see wrong with the code:
No logging to tell later what happened.
A generic exception.
Where are you returning this to? How about redirect to an error
page?
But I wouldn't mind the return within the catch block if there is need to do further processing.
I think that having a return on the catch can create bugs if after the code evolves catching more exceptions and forgets the return command.
Also looking on a more expressive code, I would say that you want to validate if the request path is numeric or not. So what do you think about this code?
#WebServlet("/processes/edit/*")
public class ProcessEditServlet extends HttpServlet {
// you may get a logger over Dependency Injection or joust create one here...
private final Logger logger;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(pathIsNotNumeric(request.getPathInfo())) {
response.sendError(404);
return;
}
request.getRequestDispatcher("/WEB-INF/processEdit.jsp").forward(request, response);
}
public boolean pathIsNotNumeric(final String pathInfo){
boolean isNotNumeric = true;
try {
Integer.parseInt(StringManipulation.removeSlashes(pathInfo));
isNotNumeric = false;
} catch (NumberFormatException e) {
logger.log(e); // logging the exception
}
return isNotNumeric;
}

NullPointerException with Servlet

I am calling a Servlet using its URL address. This is the URL I am typing
http://localhost:7001/ryan/olympics?action=selectCatalog&id=1
This is the Servlet's URL for sure; if I change the address I get
page not found
This is the code for the Servlet.
public class Servlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
}
public void init(ServletConfig config) throws ServletException {
System.out.println("*** initializing controller servlet.");
super.init(config);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("selectCatalog")) {
String categoryId = request.getParameter("id");
ProductModelDAO dao4 = new ProductModelDAOImpl("jpac");
if (categoryId != null && !categoryId.trim().equals("")) {
CategoryDAO dao1 = new CategoryDAOImpl("jpac");
try {
Category category = dao1.getCategoryName(categoryId);
request.setAttribute("category", category);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
#SuppressWarnings("unchecked")
List<Product> products = dao4
.getProductsByCategory(categoryId);
request.setAttribute("products", products);
} catch (Exception e) {
e.printStackTrace();
}
url = "SelectCatalog.jsp";
RequestDispatcher requestDispatcher =
getServletContext().getRequestDispatcher(url);
requestDispatcher.forward(request, response);
I get the NullPointerException pointing to the RequestDispatcher's line. Any help?
Try changing "SelectCatalog.jsp" to "/SelectCatalog.jsp", because, as I understand, You want to use an absolute path.
If you want to use a relative path you have to use:
request.getRequestDispatcher(url);
in place of:
getServletContext().getRequestDispatcher(url);
request.getParameter("action");
code is written in doPost method. Are you invoking this servlet from doPost method of calling servlet? URL parameters will not be used by doPost method.

Categories