IE10 document mode at the java side - java

Is there any way of getting to know IE document mode on the java servlet. Apparently, I tried to get browser information using "User-Agent" string, but i am unable to get document mode from this.

To get the document mode of IE, use below Servlet class.
Code:
public class DocumentModeOfIE extends HttpServlet {
private String documentMode;
public void init(ServletConfig config) throws ServletException {
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
documentMode = req.getHeader("X-UA-Compatible");
out.println(documentMode);
}
public void destroy() {
}
}
==============To Set the IE document mode to particular standard mode (i.e IE 7 0r IE8)==============
Code :
Using filter....
Filter Class:
public class UserAgentCompatibleFilter implements javax.servlet.Filter {
private Logger log = Logger.getLogger("UserAgentCompatibleFilter");
private String compatibilityMode;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
if (compatibilityMode != null) {
HttpServletResponse res = (HttpServletResponse) resp;
res.addHeader("X-UA-Compatible", compatibilityMode);
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
compatibilityMode = config.getInitParameter("compatibilityMode");
if (compatibilityMode == null) {
log.warn("No CompatibilityMode set for UserAgentCompatibleFilter, thus disabling it");
}
}
}
web.xml :
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- filter component start -->
<filter>
<filter-name>UserAgentCompatibleFilter</filter-name>
<filter-class>com.standardandpoors.ata.web.UserAgentCompatibleFilter</filter-class>
<init-param>
<param-name>compatibilityMode</param-name>
<param-value>IE=8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UserAgentCompatibleFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- filter component end -->
I hope this will help u most......

Related

jasig CAS: reference to RegistredService in AuthHandler Class

I'm developing a custom AuthHandler for our company.
The idea is to allow access based on user and service.
But i can't find a way to access the RegistredService.
Is there a way to pass the RegistredService to my AuthHandler ?
/**
* Mbox Auth Handler
*/
package lu.ion.cas.adaptors.mbox;
import org.jasig.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import lu.ion.cas.MboxAuthHelper;
import javax.validation.constraints.NotNull;
public class AuthHandler
extends AbstractPreAndPostProcessingAuthenticationHandler {
private MboxAuthHelper mboxAuthHelper;
private RequestContext context;
protected boolean doAuthentication(final Credentials credentials)
throws AuthenticationException {
return authenticateUsernamePasswordInternal((UsernamePasswordCredentials) credentials);
}
protected boolean authenticateUsernamePasswordInternal(
final UsernamePasswordCredentials credentials)
throws AuthenticationException {
return mboxAuthHelper.load(credentials.getUsername(), credentials.getPassword(), "/auth/check") != null;
}
public boolean supports(Credentials credentials) {
return true;
}
public final void setMboxAuthHelper(final MboxAuthHelper mboxAuthHelper) {
this.mboxAuthHelper = mboxAuthHelper;
}
}
I'm using CAS 3.5.2.
I have used CAS for a few years and found that there are many ways to do everything. I don't know how (or if) you can pass the RegisteredService to your AuthHandler. I solved the same problem by using a custom AuthenticationFilter.
(backend)
Create AuthenticationFilter.java in/near your CAS project like this:
public class AuthenticationFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
String loginName = request.getRemoteUser();
String contextPath = request.getContextPath();
System.err.println("loginName is: " + loginName);
System.err.println("contextPath is: " + contextPath);
boolean isAuthorized = false;
// do work/query to find out if they are authorized
if (isAuthorized) {
chain.doFilter(request, response);
} else {
session.invalidate();
// print error page
}
}
#Override
public void init(FilterConfig config) throws ServletException {
}
#Override
public void destroy() {
}
}
(frontend) Then add to your filter chain. If you have a web.xml with existing CAS filters, it is easy.
...
<filter>
<filter-name>Custom Filter</filter-name>
<filter-class>
com.yoursite.filter.AuthenticationFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>Custom Filter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
...
No there is no way to do this. If you want to implement authorization rules for CAS 3.5.2, you should review cas-addons:
https://github.com/Unicon/cas-addons/wiki

getting IllegalStateException within the doFilter method

When i create a servlet filter in Spring MVC, I am getting the following exception.
[javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed] with root cause
when i put the sysout i could understand that the exception occurs at the redirect line, but didn't understand why
can anyone please tell me some solution for this
SessionFilter.java
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
if(urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
}
}
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig config) throws ServletException {
System.out.println("entered init");
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringMVCHibernate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.common.dao.SessionFilter</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
:
:
:
To simple and short Answer for your Question:
To avoid this , you should have a return statement , or avoid redirecting or forwarding request , or these kind of things should be done by the last filter in the filter chain.
For More Details Explanation you can read below :
This Exception occurs when you try to send response again when the response is already committed and flushed to user.
For Example :
Here in below example code ,first the request will be forwarded to index_test.jsp and response will be flushed to user , then the control will again come back to filter and try to send another response (redirect)to user , and it will fail.
Usually we check multiple conditions in filter and accordingly forward and redirect , if two conditions are met , then it will create a problem .
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.getRequestDispatcher("index_test.jsp").forward(request, response);
((HttpServletResponse)response).sendRedirect("new.jsp");
chain.doFilter(request, response);
}
Solution for your case :
To avoid this , you should have a return statement , or avoid redirecting or forwarding request , or these kind of things should be done by the last filter in the filter chain.
So you could change your code as :
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
if(urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
return;
}
}
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig config) throws ServletException {
System.out.println("entered init");
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
Its Obvious right :
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
return;
We are have return after that statement.
So further execution wont happen so u are not getting exception.
See we cant involve both filtering and Redirect or Forward in same block it will give IllegalStateException because :
This Exception occurs when you try to send response again when the response is already committed and flushed to user

To programmatically disable IE-8 compatibility mode for the site running in intranet and rendering .xhtml pages

I have a JSF application with .xhtml pages running in intranet.I tried removing default meta tag and add the meta tag
<meta http-equiv="X-UA-Compatible" content="IE=8" />
But there is no use.Is this solution only for plain html pages or is there any other way using which i can programmatically disable compatibility mode.
If you want to prevent the compatibility mode for all your JSF pages you better use a filter for this:
Java
public class NoCompatibilityMode implements Filter {
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
if (((HttpServletRequest) req).getRequestURI().endsWith(".js.jsf")
|| ((HttpServletRequest) req).getRequestURI().endsWith(".css.jsf")) {
chain.doFilter(req, res);
} else {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("X-UA-Compatible", "IE=edge"); // No more Compatibility Mode
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
web.xml
<filter>
<filter-name>NoCompatibilityMode</filter-name>
<filter-class>my.package.name.NoCompatibilityMode</filter-class>
</filter>
<filter-mapping>
<filter-name>NoCompatibilityMode</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>

spring mvc redirect path and all children to another domain

I am trying to work out how to redirect from my webapp to another server, preserving any paths and GET vars.
eg
www.myapp.com/foo
foo.com
www.myapp.com/foo/bar
foo.com/bar
www.myapp.com/foo?bar=1
foo.com?bar=1
I would idealy just like to use something like
<mvc:view-controller path="/foo/**" view-name="redirect:http://foo.com**" />
I ended up using a filter.
infrastructurally this seems to be the simplest way
filter implementation:
public class DomainRedirectFilter extends OncePerRequestFilter {
private String destinationDomain;
private String sourceServletPath;
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String path = request.getServletPath();
path = StringUtils.replace(path, getSourceServletPath(), "");
if (request.getQueryString() != null) {
path += '?' + request.getQueryString();
}
response.setHeader( "Location", getDestinationDomain() + path );
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader( "Connection", "close" );
}
web.xml
<filter>
<filter-name>fooDomainRedirectFilter</filter-name>
<filter-class>com.abc.mvc.util.DomainRedirectFilter</filter-class>
<init-param>
<param-name>destinationDomain</param-name>
<param-value>http://foo.abc.com</param-value>
</init-param>
<init-param>
<param-name>sourceServletPath</param-name>
<param-value>/foo</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>fooDomainRedirectFilter</filter-name>
<url-pattern>/foo/*</url-pattern>
<url-pattern>/foo</url-pattern>
</filter-mapping>
I needed to add 2 url-patterns to allow for
/foo
/foo?id=1
/foo/bar
/foo/bar?id=1
You could also do this as a Handler if you are using something like Jetty.
public class DomainRedirectHandler extends HandlerWrapper {
#Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String hostName = request.getHeader("Host");
if (hostName == null) {
getHandler().handle(target, baseRequest, request, response);
return;
}
// see if the host header has a domain name that we are redirecting
hostName = hostName.toLowerCase();
int index = hostName.indexOf(':');
if (index >= 0) {
// cut off the optional port suffix
hostName = hostName.substring(0, index);
}
if (hostName.equals("some.domain.com")) {
response.sendRedirect("https://some.other.domain.com");
} else {
getHandler().handle(target, baseRequest, request, response);
}
}
}
This obviously needs to be before your content handlers in the handler chain to be effective.
Something like this should probably be done with virtual hosts through Apache.
Here's a link to some documentation:
http://httpd.apache.org/docs/2.0/vhosts/examples.html

How to use a servlet filter in Java to change an incoming servlet request url?

How can I use a servlet filter to change an incoming servlet request url from
http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123
to
http://nm-java.appspot.com/Check_License?Contact_Id=My_Obj_123
?
Update: according to BalusC's steps below, I came up with the following code:
public class UrlRewriteFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
//
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
String requestURI = request.getRequestURI();
if (requestURI.startsWith("/Check_License/Dir_My_App/")) {
String toReplace = requestURI.substring(requestURI.indexOf("/Dir_My_App"), requestURI.lastIndexOf("/") + 1);
String newURI = requestURI.replace(toReplace, "?Contact_Id=");
req.getRequestDispatcher(newURI).forward(req, res);
} else {
chain.doFilter(req, res);
}
}
#Override
public void destroy() {
//
}
}
The relevant entry in web.xml look like this:
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>com.example.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I tried both server-side and client-side redirect with the expected results. It worked, thanks BalusC!
Implement javax.servlet.Filter.
In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
Use HttpServletRequest#getRequestURI() to grab the path.
Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the #WebFilter annotation for that instead.
Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.
Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.
You could use the ready to use Url Rewrite Filter with a rule like this one:
<rule>
<from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
<to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>
Check the Examples for more... examples.
A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
public class UrlPrettyfierFilter implements Filter {
private static final String JSF_VIEW_ROOT_PATH = "/ui";
private static final String JSF_VIEW_SUFFIX = ".xhtml";
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
//Only process the paths starting with /ui, so as other requests get unprocessed.
//You can register the filter itself for /ui/* only, too
if (requestURI.startsWith(JSF_VIEW_ROOT_PATH)
&& !requestURI.contains(JSF_VIEW_SUFFIX)) {
request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
In my case, I use Spring and for some reason forward did not work with me, So I did the following:
public class OldApiVersionFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (httpServletRequest.getRequestURI().contains("/api/v3/")) {
HttpServletRequest modifiedRequest = new HttpServletRequestWrapper((httpServletRequest)) {
#Override
public String getRequestURI() {
return httpServletRequest.getRequestURI().replaceAll("/api/v3/", "/api/");
}
};
chain.doFilter(modifiedRequest, response);
} else {
chain.doFilter(request, response);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void destroy() {}
}
Make sure you chain the modifiedRequest

Categories

Resources