AbstractFacesServlet, how to implement AbstractFacesServlet.java in Java? - java

I created web-service,where i am getting url params , which i am setting it to Object.
after it when i want to set to facesContext it is giving me NULL.I got Suggestion to implement AbstractFacesServlet.java class in project but any idea how can ?
And this is what code i am using _
public class ReserRes extends ServerResource {
#Post("xml")
public void $post() throws Throwable {
...........
.....
FacesHelper.setValueBindingObject("SelectedOtaReservationBean",
reservationBean);
......
}
And setValueBindingObject(,,) is
public static final void setValueBindingObject(String expression,
final Object value) {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) // Always throwing NULL
throw new NullPointerException(
"Could not get a reference to the current Faces context");
Application application = facesContext.getApplication();
ValueBinding vb = application.createValueBinding(expression);
vb.setValue(facesContext, value);
}
In this i am not interacting with any .jsp or any kind of UI. i am getting params and binding with object. Is this wrong or any way to implement FacesContext for ws.?
I got one suggestion http://cwiki.apache.org/MYFACES/access-facescontext-from-servlet.html to use this class. any buddy know how can i implement or set object to FacesContext using this?
Thanx

Related

How to mock ServletContext getResource?

i am currently writing Junit-Tests for on OData-Application (a hobby project). In there, I initialize a Servlet with the init() function. In order to receive specific application settings, i use the context.getResource() method.
Here is my code:
#Override
public void init(ServletConfig config) {
try {
super.init(config);
ServletContext context = getServletContext();
URL resourceUrl = context.getResource("/WEB-INF/config.properties");
if (resourceUrl == null) {
throw new ConfigurationException("Unable to find config.properties");
}
Path configFile = Paths.get(resourceUrl.toURI());
Now, I try to mock it. The Servlet itself is easy to mock, but im getting error when i try to mock the "getResource"-functionality. Here is my Junit-(beforeClass) Block:
public static ODataServlet getServlet() throws MalformedURLException {
if (servlet == null) {
servletConfig = new MockServletConfig();
MockServletContext context = new MockServletContext();
Path path = Paths.get("src/test/resources/config.properties");
when(context.getResource("/WEB-INF/config.properties")).thenReturn(path.toUri().toURL());
servlet = new ODataServlet(){
/**
*
*/
private static final long serialVersionUID = 1L;
public ServletContext getServletContext() {
return context; // return the mock
}
};
servlet.init(servletConfig);
}
return servlet;
}
Unfortunately, i always get the Exception:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
In the line
when(context.getResource("/WEB-INF/config.properties")).thenReturn(path.toUri().toURL());
I dont understand why. the context-Object is a MockedObject (MockServletContext).
Any advice ? Im also thinking changing everytghing to classloader.getResource as a workaround. But actually i like it like this ...
Any help would be much appreciated.
Sephir
UPDATE: SOLVED. After literally only a few minutes in here, some guys pointed out the Issue: MockServletContext context is from the Package org.springframework.mock.web which is not working with the Mockito.
After changing the MockServletContext
MockServletContext context = new MockServletContext();
to
context = Mockito.mock(ServletContext.class);
everything is working.
Big thanks to you Guys (!).

Get Application Module during invocation of Bounded Taskflow

I have a filter which maps just before the Faces Servlet and populate some Attributes in the HttpSession before it proceeds with the request
if (_clientUser != null && !_clientUser.isEmpty()) {
session.setAttribute(CLIENT_USER_URI_PARAM_NAME, _clientUser);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
Within the URI there are some informations for which Task-flow should be addressed
faces/adf.task-flow?adf.tfId=task-flow-definition-id&adf.tfDoc=/WEB-INF/task-flow-definition-id.xml
After I proceed the request there is a method-call within the bounded task flow which is called before the view (lets call the view MainPage), by making it default activity
<default-activity>doStuff</default-activity>
The Method itself is within a PageFlowScoped Managed Bean, which is added to the task-flow-definition-id.xml
Here is the doStuff Method which is called before the "MainPage"-View
public class Controller{
public void doStuff {
FacesContext ctx = FacesContext.getCurrentInstance();
Map sessionMap = ctx.getExternalContext().getSessionMap();
String clientUser = (String) sessionMap.get(CLIENT_USER_URI_PARAM_NAME);
AppModImpl am = getApplicationModule();
DBTransaction transaction = am.getDBTransaction();
//do more stuff
}
}
public AppModImpl getApplicationModule() {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data.AppModDataControl.dataProvider}", Object.class);
AppModImpl am = (AppModImpl) valueExp.getValue(elContext);
return am;
}
Everything works fine till here. But if I try to get the Application Module. There is non.
This application normally doesn't have any DataControl, because is just a root Application which holds different components which have been added by ADFLibrarys, but I added an DataControl to the DataBindings.cpx and a iterator to the MainPagePageDef (just to include a DataControl in the bindings) but still no result.
Do you have any advice for me how I can access the Application Module? FacesServlet should have been already created the necessary FacesContext by the time the Managed Bean is called or does it only create a new FacesContext the Time an actual Page (jspx/jsf) loads?
I've found myself an answer:
Here is the Block Post which helped me figure it out.
http://andrejusb.blogspot.de/2012/02/how-to-fix-data-control-initialization.html

Custom Annotation JSF

I wanted to make a custom annotation to check security on some functions for my JSF web application. For security I use Tomcat security with JaaS, so I have no application managed security to my disposal.
What actually want to do is make an annotation for my methods in the Backing Beans like Spring Security (#Secured("role")). My security system is implemented so that every function is a role and you can dynamically make "user roles" these are stored in the DB and when somebody logs in all the (function)roles in that "user role" will be set in tomcat security as roles.
So now I have this piece of code to check if my user can access the function:
public static void checkSecurity(final String function) {
final FacesContext facesContext = FacesContext.getCurrentInstance();
try {
if (facesContext.getExternalContext().getRemoteUser() == null) {
facesContext.getExternalContext().redirect("login.xhtml");
return;
}
if (!facesContext.getExternalContext().isUserInRole(function)) {
facesContext.getExternalContext().redirect("restricted.xhtml");
return;
}
} catch (final Exception ex /* Mandatory "IOException e" will be caught + all other exceptions. */) {
facesContext.getExternalContext().setResponseStatus(403); // HTTP Status 403: Forbidden. Can also throw 401.
facesContext.responseComplete();
}
}
Now I have to call this SecurityUtil.checkSecurity("name_of_function"); in every method.
But I want to have an annotation like this #CustomSecurity("function_name_role").
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface CustomSecurity {
// Single Element called value.
String value();
}
And when a method has this annotation the checkSecurity function automatically has to be performed. So I have to scan for this annotation at a point, or make some kind of actionlistener. JSF should have some options for this but all the forums I found on this don't really help.
Does somebody has some ideas?
EDIT:
I tried this blog it works but only on an action of a component (and components don't render when you don't have the role). So how secure is this when people try to hack into the JSF structure. And I rather have it running on every method.
public class SecurityActionListener extends ActionListenerImpl implements ActionListener {
private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger();
#SuppressWarnings("unused")
#Override
public void processAction(final ActionEvent event) {
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final ConfigurableNavigationHandler navHandler = (ConfigurableNavigationHandler) application.getNavigationHandler();
// Action stuff
final UIComponent source = event.getComponent();
final ActionSource actionSource = (ActionSource) source;
MethodBinding binding;
binding = actionSource.getAction();
final String expr = binding.getExpressionString();
if (!expr.startsWith("#")) {
super.processAction(event);
return;
}
final int idx = expr.indexOf('.');
final String target = expr.substring(0, idx).substring(2);
final String t = expr.substring(idx + 1);
final String method = t.substring(0, (t.length() - 1));
final MethodExpression expression = new MethodExpressionMethodBindingAdapter(binding);
final ELContext elContext = context.getELContext();
final ExpressionFactory factory = context.getApplication().getExpressionFactory();
final ValueExpression ve = factory.createValueExpression(elContext, "#{" + target + '}', Object.class);
final Object result = ve.getValue(elContext);
// Check if the target method is a secured method
// and check security accordingly
final Method[] methods = result.getClass().getMethods();
for (final Method meth : methods) {
if (meth.getName().equals(method)) {
if (meth.isAnnotationPresent(CustomSecurity.class)) {
final CustomSecurity securityAnnotation = meth.getAnnotation(CustomSecurity.class);
System.out.println("Function to check security on: " + securityAnnotation.value()); // TODO TO LOG
SecurityUtil.checkSecurity(securityAnnotation.value());
} else {
super.processAction(event);
}
break;
}
}
}
}
And this in the faces-config.xml:
<action-listener>
com.nielsr.randompackagebecauseofnda.SecurityActionListener
</action-listener>
This blog could also be an answer, but I don't know how it will work with my JaaS Tomcat security because the security is in a separate project deployed as a standalone JAR in the tomcat lib folder.
But I actually don't know that I have to secure my Beans. Because I have configured all the functions (aka roles see above) that are on 1 page in the Web.xml as security constraints. And I render the components on the page only if you have to rights or "function_role" on that component. So is this secured enough? Or if somebody has a right to a function on a page can he render the components himself and so hack my site?
I'm not that familiar to JSF to know this, what is going on in that extra JSF abstraction layer between Controller and View? (I'm more of a Spring MVC developer, but because of requirements I have to use JSF but it's nice to broaden my knowledge.)
You can "scan for your Annotations" using
http://code.google.com/p/reflections/
Regards

Capturing parameters of a method at runtime in Java

Our application uses several back-end services and we maintain wrappers which contain the methods to make the actual service calls. If any exception occurs in any of those methods while invoking a service, we throw a custom exception encapsulating the original exception as shown below.
interface IServiceA {
public void submit(String user, String attributes);
}
public class ServiceAWrapper implements IserviceA {
private ActualService getActualService() {
.....
}
public void submit(String user, String attributes) {
try {
Request request = new Request();
request.setUser(user);
request.setAttributes(attributes);
getActualService().call(request);
} catch(ServiceException1 e) {
throw new MyException(e, reason1);
} catch(ServiceException2 e) {
throw new MyException(e, reason2);
}
}
}
I would like to know if there's any framework that would allow me to
capture (and probably log) all the
parameters passed to my wrapper
methods at run-time; if the methods
are called.
capture the actual exception
object(MyException instance in above
example), if any thrown; so that I
could append the passed parameters
to the object at run-time.
I am currently exploring AspectJ to see if it can address my requirements, but I am not sure if it can be used to capture the parameters passed to methods at runtime and also to capture exception objects, if any occur.
Thanks.
With AspectJ, you can use around advice to execute advice instead of the code at the join point. You can then execute the actual join-point from within the advice by calling proceed. This would allow you to capture the input parameters, log them, and proceed to call the actual method.
Within the same advice you could capture any logs throw from the method, and inspect or log them before passing it back up to higher levels.
Matt B's answer is right. Specifically, you can do something like this:
aspect MonitorServiceCalls {
private final Logger LOG = LoggerFactory.getLog("ServiceCallLog");
Object around() throws MyException: call(public * *(..) throws MyException)
&& target(IServiceA+) {
MethodSignature msig = (MethodSignature)thisJoinPoint;
String fullMethName = msig.getMethod().toString();
try {
Object result = proceed();
LOG.info("Successful call to {} with arguments {}",
fullMethName,
thisJoinPoint.getArgs());
return result;
} catch(MyException e) {
LOG.warn("MyException thrown from {}: {}", msig.getMethod(), e);
throw e;
}
}
}
AspectJ is the right option. You will be able to get hold of the parameters by way of a JoinPoint object that will be passed to your advise methods. You can also get hold of the exception either by implementing an after throwing advise or an around advise.

Calling application.getRealPath() from within a class in JSP

I am writing a class in JSP to retrieve a bunch of config values from an XML file. My plan is to have a class "XMLConfig" that loads in the values from the file, and then uses access methods to get at the values in the config object.
My problem is that i cannot seem to call application.getRealPath() from within the class, since eclipse tells me that "application cannot be resolved". I suspect that I must change "application" to something else but I am unsure what.
My code for the class:
<%!
//Config object
public class XMLConfig {
public boolean loadConfigFile(String strName) {
String XMLfileName = application.getRealPath(strName);
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = null;
doc = db.parse(XMLFileName);
}catch(Exception e)
{
System.out.println(e.getMessage());
return false;
}
return true;
}
}
%>
application isn't a global var. If you want to use it in your method then you'll need to pass it as a parameter.
Not sure why you're defining the class within the jsp though instead of just creating a 'normal' java class.
That's a job for a servlet instead of JSP. Create a class which extends HttpServlet and implement the doGet() method as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strName = getOrDefineItSomehow();
Document doc = loadConfigFile(getServletContext().getRealPath(strName));
// Do whatever you want with it and then display JSP page.
request.getRequestDispatcher("/WEB-INF/config.jsp").forward(request, response);
}
Map this servlet in web.xml on an url-pattern of for example /config and invoke it by for example http://example.com/context/config. It'll run the code in doGet().
See also:
Beginning and intermediate JSP/Servlet tutorials
How to avoid Java code in JSP?
Hidden features of JSP/Servlet

Categories

Resources