Search code examples
jsf-2primefacesprettyfaces

Mobile site prefix and jsf 2


How can you implement the common mobile site patterns easily with jsf2? Can i achieve it with prettyfaces?

Basically i want:

m.mysite/index renders mobileIndex.xhtml mysite/index renders index.xhtml

I want the "m." prefix specifically and I can't figure out how.

Using primefaces, tomcat7 and prettyfaces. Cheers


Solution

  • The complete solution for you question is posted on the Primefaces forum and can be found here here

    Here is the relevant code:

    The ViewHandler code

    import java.util.Map;
    import javax.faces.application.ViewHandler;
    import javax.faces.application.ViewHandlerWrapper;
    import javax.faces.context.FacesContext;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.http.HttpServletRequest;
    
    public class MyViewHandlerWrapper extends ViewHandlerWrapper {
    
        private ViewHandler wrapped;
    
        public KxRenderKit(ViewHandler wrapped) {
            this.wrapped = wrapped;
        }
    
        @Override
        public ViewHandler getWrapped() {
            return this.wrapped;
        }
    
        @Override
        public String calculateRenderKitId(FacesContext context) {
    
            HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
            String userAgent = req.getHeader("user-agent");
            String accept = req.getHeader("Accept");
    
            if (userAgent != null && accept != null) {
                UserAgentInfo agent = new UserAgentInfo(userAgent, accept);
                if (agent.isMobileDevice()) {
                    return "PRIMEFACES_MOBILE";
                }
            }
    
            return this.wrapped.calculateRenderKitId(context);
        }
    }
    

    Implementation inside your Managed Bean

    @PostConstruct
        public void myPostConstruct(){
            String renderKitId = FacesContext.getCurrentInstance().getViewRoot().getRenderKitId();        
            if(renderKitId.equalsIgnoreCase("PRIMEFACES_MOBILE")){
                //REDIRECT TO YOUR MOBILE PAGE
            }
        }
    

    UserAgent detection code

    UserAgent detection code

    /* *******************************************
    // Copyright 2010-2012, Anthony Hand
    //
    // File version date: April 23, 2012
    //      Update:
    //      - Updated DetectAmazonSilk(): Fixed an issue in the detection logic.  
    //
    // File version date: April 22, 2012 - Second update
    //      Update: To address additional Kindle issues...
    //      - Updated DetectRichCSS(): Excluded e-Ink Kindle devices. 
    //      - Created DetectAmazonSilk(): Created to detect Kindle Fire devices in Silk mode. 
    //      - Updated DetectMobileQuick(): Updated to include e-Ink Kindle devices and the Kindle Fire in Silk mode.  
    //
    // File version date: April 11, 2012
    //      Update: 
    //      - Added a new variable for the new BlackBerry Curve Touch (9380): deviceBBCurveTouch. 
    //      - Updated DetectBlackBerryTouch() to support the new BlackBerry Curve Touch (9380).
    //
    // File version date: January 21, 2012
    //      Update: 
    //      - Moved Windows Phone 7 to the iPhone Tier. WP7.5's IE 9-based browser is good enough now.  
    //      - Added a new variable for 2 versions of the new BlackBerry Bold Touch (9900 and 9930): deviceBBBoldTouch. 
    //      - Updated DetectBlackBerryTouch() to support the 2 versions of the new BlackBerry Bold Touch (9900 and 9930). 
    //      - Updated DetectKindle() to focus on eInk devices only. The Kindle Fire should be detected as a regular Android device.
    //
    // File version date: August 22, 2011
    //      Update: 
    //      - Updated DetectAndroidTablet() to fix a bug I introduced in the last fix!
    //
    // File version date: August 16, 2011
    //      Update: 
    //      - Updated DetectAndroidTablet() to exclude Opera Mini, which was falsely reporting as running on a tablet device when on a phone.
    //
    //
    // LICENSE INFORMATION
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //        http://www.apache.org/licenses/LICENSE-2.0
    // Unless required by applicable law or agreed to in writing,
    // software distributed under the License is distributed on an
    // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
    // either express or implied. See the License for the specific
    // language governing permissions and limitations under the License. 
    //
    //
    // ABOUT THIS PROJECT
    //   Project Owner: Anthony Hand
    //   Email: anthony.hand@gmail.com
    //   Web Site: http://www.mobileesp.com
    //   Source Files: http://code.google.com/p/mobileesp/
    //
    //   Versions of this code are available for:
    //      PHP, JavaScript, Java, ASP.NET (C#), and Ruby
    //
    // *******************************************
     */
    package com.handinteractive.mobile;
    
    /**
     * The DetectSmartPhone class encapsulates information about
     *   a browser's connection to your web site.
     *   You can use it to find out whether the browser asking for
     *   your site's content is probably running on a mobile device.
     *   The methods were written so you can be as granular as you want.
     *   For example, enquiring whether it's as specific as an iPod Touch or
     *   as general as a smartphone class device.
     *   The object's methods return true, or false.
     */
    public class UAgentInfo {
        // User-Agent and Accept HTTP request headers
    
        private String userAgent = "";
        private String httpAccept = "";
    
        // Let's store values for quickly accessing the same info multiple times.
        public boolean isIphone = false;
        public boolean isAndroidPhone = false;
        public boolean isTierTablet = false;
        public boolean isTierIphone = false;
        public boolean isTierRichCss = false;
        public boolean isTierGenericMobile = false;
    
        // Initialize some initial smartphone string variables.
        public static final String engineWebKit = "webkit";
    
        public static final String deviceIphone = "iphone";
        public static final String deviceIpod = "ipod";
        public static final String deviceIpad = "ipad";
        public static final String deviceMacPpc = "macintosh"; //Used for disambiguation
    
        public static final String deviceAndroid = "android";
        public static final String deviceGoogleTV = "googletv";
        public static final String deviceXoom = "xoom"; //Motorola Xoom
        public static final String deviceHtcFlyer = "htc_flyer"; //HTC Flyer
    
        public static final String deviceSymbian = "symbian";
        public static final String deviceS60 = "series60";
        public static final String deviceS70 = "series70";
        public static final String deviceS80 = "series80";
        public static final String deviceS90 = "series90";
    
        public static final String deviceWinPhone7 = "windows phone os 7";
        public static final String deviceWinMob = "windows ce";
        public static final String deviceWindows = "windows";
        public static final String deviceIeMob = "iemobile";
        public static final String devicePpc = "ppc"; //Stands for PocketPC
        public static final String enginePie = "wm5 pie"; //An old Windows Mobile
    
        public static final String deviceBB = "blackberry";
        public static final String vndRIM = "vnd.rim"; //Detectable when BB devices emulate IE or Firefox
        public static final String deviceBBStorm = "blackberry95";  //Storm 1 and 2
        public static final String deviceBBBold = "blackberry97";  //Bold 97x0 (non-touch)
        public static final String deviceBBBoldTouch = "blackberry 99";  //Bold 99x0 (touchscreen)
        public static final String deviceBBTour = "blackberry96";  //Tour
        public static final String deviceBBCurve = "blackberry89";  //Curve 2
        public static final String deviceBBCurveTouch = "blackberry 938";  //Curve Touch 9380
        public static final String deviceBBTorch = "blackberry 98";  //Torch
        public static final String deviceBBPlaybook = "playbook"; //PlayBook tablet
    
        public static final String devicePalm = "palm";
        public static final String deviceWebOS = "webos"; //For Palm's line of WebOS devices
        public static final String deviceWebOShp = "hpwos"; //For HP's line of WebOS devices
    
        public static final String engineBlazer = "blazer"; //Old Palm
        public static final String engineXiino = "xiino"; //Another old Palm
    
        public static final String deviceKindle = "kindle";  //Amazon Kindle, eInk one
        public static final String engineSilk = "silk";  //Amazon's accelerated Silk browser for Kindle Fire
    
        public static final String deviceNuvifone = "nuvifone";  //Garmin Nuvifone
    
        //Initialize variables for mobile-specific content.
        public static final String vndwap = "vnd.wap";
        public static final String wml = "wml";
    
        //Initialize variables for other random devices and mobile browsers.
        public static final String deviceTablet = "tablet"; //Generic term for slate and tablet devices
        public static final String deviceBrew = "brew";
        public static final String deviceDanger = "danger";
        public static final String deviceHiptop = "hiptop";
        public static final String devicePlaystation = "playstation";
        public static final String deviceNintendoDs = "nitro";
        public static final String deviceNintendo = "nintendo";
        public static final String deviceWii = "wii";
        public static final String deviceXbox = "xbox";
        public static final String deviceArchos = "archos";
    
        public static final String engineOpera = "opera"; //Popular browser
        public static final String engineNetfront = "netfront"; //Common embedded OS browser
        public static final String engineUpBrowser = "up.browser"; //common on some phones
        public static final String engineOpenWeb = "openweb"; //Transcoding by OpenWave server
        public static final String deviceMidp = "midp"; //a mobile Java technology
        public static final String uplink = "up.link";
        public static final String engineTelecaQ = "teleca q"; //a modern feature phone browser
        public static final String devicePda = "pda"; //some devices report themselves as PDAs
        public static final String mini = "mini";  //Some mobile browsers put "mini" in their names.
        public static final String mobile = "mobile"; //Some mobile browsers put "mobile" in their user agent strings.
        public static final String mobi = "mobi"; //Some mobile browsers put "mobi" in their user agent strings.
    
        //Use Maemo, Tablet, and Linux to test for Nokia"s Internet Tablets.
        public static final String maemo = "maemo";
        public static final String linux = "linux";
        public static final String qtembedded = "qt embedded"; //for Sony Mylo
        public static final String mylocom2 = "com2"; //for Sony Mylo also
    
        //In some UserAgents, the only clue is the manufacturer.
        public static final String manuSonyEricsson = "sonyericsson";
        public static final String manuericsson = "ericsson";
        public static final String manuSamsung1 = "sec-sgh";
        public static final String manuSony = "sony";
        public static final String manuHtc = "htc"; //Popular Android and WinMo manufacturer
    
        //In some UserAgents, the only clue is the operator.
        public static final String svcDocomo = "docomo";
        public static final String svcKddi = "kddi";
        public static final String svcVodafone = "vodafone";
    
        //Disambiguation strings.
        public static final String disUpdate = "update"; //pda vs. update
    
    
        /**
         * Initialize the userAgent and httpAccept variables
         *
         * @param userAgent the User-Agent header
         * @param httpAccept the Accept header
         */
        public UAgentInfo(String userAgent, String httpAccept) {
            if (userAgent != null) {
                this.userAgent = userAgent.toLowerCase();
            }
            if (httpAccept != null) {
                this.httpAccept = httpAccept.toLowerCase();
            }
    
            //Intialize key stored values.
            initDeviceScan();
        }
    
        /**
         * Return the lower case HTTP_USER_AGENT
         * @return userAgent
         */
        public String getUserAgent() {
            return userAgent;
        }
    
        /**
         * Return the lower case HTTP_ACCEPT
         * @return httpAccept
         */
        public String getHttpAccept() {
            return httpAccept;
        }
    
        /**
         * Return whether the device is an Iphone or iPod Touch
         * @return isIphone
         */
        public boolean getIsIphone() {
            return isIphone;
        }
    
        /**
         * Return whether the device is in the Tablet Tier.
         * @return isTierTablet
         */
        public boolean getIsTierTablet() {
            return isTierTablet;
        }
    
        /**
         * Return whether the device is in the Iphone Tier.
         * @return isTierIphone
         */
        public boolean getIsTierIphone() {
            return isTierIphone;
        }
    
        /**
         * Return whether the device is in the 'Rich CSS' tier of mobile devices.
         * @return isTierRichCss
         */
        public boolean getIsTierRichCss() {
            return isTierRichCss;
        }
    
        /**
         * Return whether the device is a generic, less-capable mobile device.
         * @return isTierGenericMobile
         */
        public boolean getIsTierGenericMobile() {
            return isTierGenericMobile;
        }
    
        /**
         * Initialize Key Stored Values.
         */
        public void initDeviceScan() {
            this.isIphone = detectIphoneOrIpod();
            this.isAndroidPhone = detectAndroidPhone();
            this.isTierTablet = detectTierTablet();
            this.isTierIphone = detectTierIphone();
            this.isTierRichCss = detectTierRichCss();
            this.isTierGenericMobile = detectTierOtherPhones();
        }
    
        /**
         * Detects if the current device is an iPhone.
         * @return detection of an iPhone
         */
        public boolean detectIphone() {
            // The iPad and iPod touch say they're an iPhone! So let's disambiguate.
            if (userAgent.indexOf(deviceIphone) != -1 && 
                    !detectIpad() && 
                    !detectIpod()) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current device is an iPod Touch.
         * @return detection of an iPod Touch
         */
        public boolean detectIpod() {
            if (userAgent.indexOf(deviceIpod) != -1) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current device is an iPad tablet.
         * @return detection of an iPad
         */
        public boolean detectIpad() {
            if (userAgent.indexOf(deviceIpad) != -1
                    && detectWebkit()) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current device is an iPhone or iPod Touch.
         * @return detection of an iPhone or iPod Touch
         */
        public boolean detectIphoneOrIpod() {
            //We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay.
            if (userAgent.indexOf(deviceIphone) != -1
                    || userAgent.indexOf(deviceIpod) != -1) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects *any* iOS device: iPhone, iPod Touch, iPad.
         * @return detection of an Apple iOS device
         */
        public boolean detectIos() {
            if (detectIphoneOrIpod() || detectIpad()) {
                return true;
            }
            return false;
        }
    
    
        /**
         * Detects *any* Android OS-based device: phone, tablet, and multi-media player.
         * Also detects Google TV.
         * @return detection of an Android device
         */
        public boolean detectAndroid() {
            if ((userAgent.indexOf(deviceAndroid) != -1) ||
              detectGoogleTV()) 
                return true;
            //Special check for the HTC Flyer 7" tablet. It should report here.
            if (userAgent.indexOf(deviceHtcFlyer) != -1)
                return true;
            return false;
        }
    
        /**
         * Detects if the current device is a (small-ish) Android OS-based device
         * used for calling and/or multi-media (like a Samsung Galaxy Player).
         * Google says these devices will have 'Android' AND 'mobile' in user agent.
         * Ignores tablets (Honeycomb and later).
         * @return  detection of an Android phone
         */
        public boolean detectAndroidPhone() {
            if (detectAndroid() && (userAgent.indexOf(mobile) != -1)) 
                return true;
            //Special check for Android phones with Opera Mobile. They should report here.
            if (detectOperaAndroidPhone()) 
                return true;
            //Special check for the HTC Flyer 7" tablet. It should report here.
            if (userAgent.indexOf(deviceHtcFlyer) != -1) 
                return true;
            return false;
        }
    
        /**
         * Detects if the current device is a (self-reported) Android tablet.
         * Google says these devices will have 'Android' and NOT 'mobile' in their user agent.
         * @return detection of an Android tablet
         */
        public boolean detectAndroidTablet() {
            //First, let's make sure we're on an Android device.
            if (!detectAndroid())
                return false;
    
            //Special check for Opera Android Phones. They should NOT report here.
            if (detectOperaMobile()) 
                return false;
            //Special check for the HTC Flyer 7" tablet. It should NOT report here.
            if (userAgent.indexOf(deviceHtcFlyer) != -1)
                return false;
    
            //Otherwise, if it's Android and does NOT have 'mobile' in it, Google says it's a tablet.
            if ((userAgent.indexOf(mobile) > -1)) 
                return false;
            else 
                return true;
        }
    
        /**
         * Detects if the current device is an Android OS-based device and
         * the browser is based on WebKit.
         * @return detection of an Android WebKit browser
         */
        public boolean detectAndroidWebKit() {
            if (detectAndroid() && detectWebkit()) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current device is a GoogleTV.
         * @return detection of GoogleTV
         */
        public boolean detectGoogleTV() {
            if (userAgent.indexOf(deviceGoogleTV) != -1) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current browser is based on WebKit.
         * @return detection of a WebKit browser
         */
        public boolean detectWebkit() {
            if (userAgent.indexOf(engineWebKit) != -1) {
                return true;
            }
            return false;
        }
    
        /**
         * Detects if the current browser is the Symbian S60 Open Source Browser.
         * @return detection of Symbian S60 Browser
         */
        public boolean detectS60OssBrowser() {
            //First, test for WebKit, then make sure it's either Symbian or S60.
            if (detectWebkit()
                    && (userAgent.indexOf(deviceSymbian) != -1
                    || userAgent.indexOf(deviceS60) != -1)) {
                return true;
            }
            return false;
        }
    

    code continued in another answer