Friday, June 21, 2013

How to show browser info(name,version) and OS name using java in client side.


step1 - use this google api for user agent string parsing.

http://code.google.com/p/user-agent-parser-java/

or
 UserAgentDetails.java

package com.demo;


public class UserAgentDetails {

    private String browserName;
    private String browserVersion;
    private String browserComments;

      UserAgentDetails(String browserName, String browserVersion, String browserComments) {
        this.browserName = browserName;
        this.browserVersion = browserVersion;
        this.browserComments = browserComments;
    }

    public String getBrowserComments() {
        return browserComments;
    }

    public String getBrowserName() {
        return browserName;
    }

    public String getBrowserVersion() {
        return browserVersion;
    }

}

UserAgentParser.java

package com.demo;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class UserAgentParser
{
    private String userAgentString;
    private String browserName;
    private String browserVersion;
    private String browserOperatingSystem;
    private List<UserAgentDetails> parsedBrowsers = new ArrayList<UserAgentDetails>();

    private static Pattern pattern = Pattern.compile(
            "([^/\\s]*)(/([^\\s]*))?(\\s*\\[[a-zA-Z][a-zA-Z]\\])?" +
            "\\s*(\\((([^()]|(\\([^()]*\\)))*)\\))?\\s*");

    /**
     * Parses the incoming user agent string into useful data about
     * the browser and its operating system.
     * @param userAgentString the user agent header from the browser.
     */
    public UserAgentParser(String userAgentString) {
        this.userAgentString = userAgentString;
        Matcher matcher = pattern.matcher(userAgentString);

        while (matcher.find()) {
            /*
            for(int i=0; i< matcher.groupCount(); i++) {
                System.err.println(i +": " + matcher.group(i));
            }
            */
            String nextBrowserName = matcher.group(1);
            String nextBrowserVersion = matcher.group(3);
            String nextBrowserComments = null;
            if (matcher.groupCount() >= 6) {
                nextBrowserComments = matcher.group(6);
            }
            parsedBrowsers.add(new UserAgentDetails(nextBrowserName,
                    nextBrowserVersion, nextBrowserComments));
          
        }
      
        if (parsedBrowsers.size() > 0) {
            processBrowserDetails();
        } else {
           
        }

    }

    /**
     * Wraps the process of extracting browser name, version, and
     * operating sytem.
     */
    private void processBrowserDetails() {

        String[] browserNameAndVersion = extractBrowserNameAndVersion();
        browserName = browserNameAndVersion[0];
        browserVersion = browserNameAndVersion[1];

        browserOperatingSystem = extractOperatingSystem(parsedBrowsers.get(0).getBrowserComments());

    }

     private String[] extractBrowserNameAndVersion() {

        String[] knownBrowsers = new String[] {
            "firefox", "netscape", "chrome", "safari", "camino", "mosaic", "opera",
            "galeon"
        };

        for(UserAgentDetails nextBrowser : parsedBrowsers) {
            for (String nextKnown : knownBrowsers) {
                if (nextBrowser.getBrowserName().toLowerCase().startsWith(nextKnown)) {
                    return new String[] { nextBrowser.getBrowserName(), nextBrowser.getBrowserVersion() };
                }
                // TODO might need special case here for Opera's dodgy version
            }

        }
        UserAgentDetails firstAgent = parsedBrowsers.get(0);
        if (firstAgent.getBrowserName().toLowerCase().startsWith("mozilla")) {

            if (firstAgent.getBrowserComments() != null) {
                String[] comments = firstAgent.getBrowserComments().split(";");
                if (comments.length > 2 && comments[0].toLowerCase().startsWith("compatible")) {
                    String realBrowserWithVersion = comments[1].trim();
                    int firstSpace = realBrowserWithVersion.indexOf(' ');
                    int firstSlash = realBrowserWithVersion.indexOf('/');
                    if ((firstSlash > -1 && firstSpace > -1) ||
                            (firstSlash > -1 && firstSpace == -1)) {
                        // we have slash and space, or just a slash,
                        // so let's choose slash for the split
                        return new String[] {
                            realBrowserWithVersion.substring(0, firstSlash),
                            realBrowserWithVersion.substring(firstSlash+1)
                        };
                    }
                    else if (firstSpace > -1) {
                        return new String[] {
                           realBrowserWithVersion.substring(0, firstSpace),
                           realBrowserWithVersion.substring(firstSpace+1)
                        };
                    }
                    else { // out of ideas for version, or no version supplied
                        return new String[] { realBrowserWithVersion, null };
                    }
                }
            }

            // Looks like a *real* Mozilla :-)
            if (new Float(firstAgent.getBrowserVersion()) < 5.0) {
                return new String[] { "Netscape", firstAgent.getBrowserVersion() };
            } else {
                // TODO: get version from comment string
                return new String[] { "Mozilla",
                    firstAgent.getBrowserComments().split(";")[0].trim() };
            }
        } else {
            return new String[] {
                firstAgent.getBrowserName(), firstAgent.getBrowserVersion()
            };
        }
      
    }

       private String extractOperatingSystem(String comments) {

        if (comments == null) {
            return null;
        }

        String[] knownOS = new String[] { "win", "linux", "mac", "freebsd", "netbsd",
                "openbsd", "sunos", "amiga", "beos", "irix", "os/2", "warp", "iphone" };
        List<String> osDetails = new ArrayList<String>();
        String[] parts = comments.split(";");
        for (String comment : parts) {
            String lowerComment = comment.toLowerCase().trim();
            for (String os : knownOS) {
                if (lowerComment.startsWith(os)) {
                    osDetails.add(comment.trim());
                }
            }
          
        }
        switch (osDetails.size()) {
            case 0: { return null; }
            case 1: { return osDetails.get(0); }
            default: {
                return osDetails.get(0);
            }
        }

    }

       public String getBrowserName() {
        return browserName;
    }


    public String getBrowserVersion() {
        return browserVersion;
    }


    public String getBrowserOperatingSystem() {
        return browserOperatingSystem;
    }


}





step 2.


String userAgent = request.getHeader("User-Agent");
        UserAgentParser userAgentParser = new UserAgentParser(userAgent);


        String str = "Browser Name:" + userAgentParser.getBrowserName() + " Browser Version:" + userAgentParser.getBrowserVersion() + "OS Name:"
                + userAgentParser.getBrowserOperatingSystem();

How to check FileReader support this browser on not.(Drag,Drop);.


Drag drop file uploading doesn't  support all browser.
Please find this post  here

it's not working IE 9,8,7 and IE 10 compatibility view.

for this issue i have created this post how to check current browser support on not.
find this javascript code bellow.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <script type="text/javascript">
  <!--
    function check(){
    if (typeof window.FileReader === 'undefined') {
  alert('fail');
} else {
 
  alert('success');
}   
    }


  //-->
  </script>
 </head >

 <body onload="check()">
 
 </body>
</html>

Thursday, June 20, 2013

How to print selected area in zk

Step 1.
 add <zk xmlns:w="client">  tag.

Step 2.

    <button label="Print">
        <attribute w:name="onClick">
            print(this,'group',500,800,true);//
        </attribute>
    </button>
Parameter group box.
1. "group" id of groupbox.
2. 500 windows height.
3. 800 windows width.
4. true for style if true style will apply otherwise style not apply.




Full Page


 Print listbox with style
 code
    print Listbox with style:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'box1',500,800,true);
        </attribute>
    </button>
    <listbox id="box1" multiple="true" checkmark="true">

 Print Groupbox.

code.
Print Box Area:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'group',500,800,true);
        </attribute>
    </button>
<groupbox id="group" >
 Print Grid.
code.
        print Grid:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'grid',500,800,true);
        </attribute>
    </button>
    <grid id="grid">
 Print Listbox without style
code.
    print Listbox without style:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'box',500,800,false);
        </attribute>
    </button>
    <listbox id="box" multiple="true" checkmark="true">




 Full source code.
print.zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk xmlns:w="client">
<script><![CDATA[
function print(obj,id,height,width,style) {
DispWin = window.open('', '', 'toolbar=no,memubar=no,scrollbars=yes,status=no,width='+width+'px,height='+height+"px'");

DispWin.document.write('<html><head>');
if(style==true){
for(var i=0;i<document.styleSheets.length;i++){
    if(document.styleSheets[i].href != null)        {
        DispWin.document.write('<link rel="stylesheet" type="text/css" href="'+document.styleSheets[i].href+'">');
    }
}
}
DispWin.document.write('</head>');
DispWin.document.write('<body>');
DispWin.document.write('<p align="center"><input type="button" value="Close" onclick="window.close()"/>&nbsp&nbsp&nbsp&nbsp<input type="button" value="Print" onclick="print()"/></p>');
DispWin.document.write($(obj.$f(id)).formhtml());
DispWin.document.write('</body></html>');
DispWin.document.close();
//DispWin.close();
//DispWin.print();


(function($) {
      var oldHTML = $.fn.html;

      $.fn.formhtml = function() {
        if (arguments.length) return oldHTML.apply(this,arguments);
        $("input,button", this).each(function() {
          this.setAttribute('value',this.value);   
          this.setAttribute('readonly',true);
        });
        $("textarea", this).each(function() {
          // updated - thanks Raja!
          this.innerHTML = this.value;
        });
        $("input:radio,input:checkbox", this).each(function() {
          // im not really even sure you need to do this for "checked"
          // but what the heck, better safe than sorry
          if (this.checked) this.setAttribute('checked', 'checked');
          else this.removeAttribute('checked');
        });
        $("option", this).each(function() {
          // also not sure, but, better safe...
          if (this.selected) this.setAttribute('selected', 'selected');
          else this.removeAttribute('selected');
        });
        return oldHTML.apply(this);
      };

      //optional to override real .html() if you want
      // $.fn.html = $.fn.formhtml;
    })(jQuery);


]]></script>
Print Box Area:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'group',500,800,true);
        </attribute>
    </button>
<groupbox id="group" >
<caption
                label="Box"
                sclass="group-header"/>
    print Listbox with style:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'box1',500,800,true);
        </attribute>
    </button>
    <listbox id="box1" multiple="true" checkmark="true">
        <listhead>
            <listheader label="Name" />
            <listheader label="Gender" />
            <listheader label="Age" />
        </listhead>
        <listitem>
            <listcell label="Mary" />
            <listcell label="FEMALE" />
            <listcell label="18" />
        </listitem>
        <listitem>
            <listcell label="John" />
            <listcell label="MALE" />
            <listcell label="20" />
        </listitem>
        <listitem>
            <listcell label="Jane" />
            <listcell label="FEMALE" />
            <listcell label="32" />
        </listitem>
        <listitem>
            <listcell label="Henry" />
            <listcell label="MALE" />
            <listcell label="29" />
        </listitem>
        <listitem>
            <listcell label="Mark" />
            <listcell label="MALE" />
            <listcell label="15" />
        </listitem>
    </listbox>
    print Listbox without style:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'box',500,800,false);
        </attribute>
    </button>
    <listbox id="box" multiple="true" checkmark="true">
        <listhead>
            <listheader label="Name" />
            <listheader label="Gender" />
            <listheader label="Age" />
        </listhead>
        <listitem>
            <listcell label="Mary" />
            <listcell label="FEMALE" />
            <listcell label="18" />
        </listitem>
        <listitem>
            <listcell label="John" />
            <listcell label="MALE" />
            <listcell label="20" />
        </listitem>
        <listitem>
            <listcell label="Henry" />
            <listcell label="MALE" />
            <listcell label="29" />
        </listitem>
        <listitem>
            <listcell label="Mark" />
            <listcell label="MALE" />
            <listcell label="15" />
        </listitem>
        <listitem>
            <listcell label="Jeffery" />
            <listcell label="MALE" />
            <listcell label="17" />
        </listitem>
    </listbox>
        print Grid:
    <button label="Print">
        <attribute w:name="onClick">
            print(this,'grid',500,800,true);
        </attribute>
    </button>
    <grid id="grid">
    <auxhead>
        <auxheader label="H1'07" colspan="6"/>
        <auxheader label="H2'07" colspan="6"/>
    </auxhead>
    <auxhead>
        <auxheader label="Q1" colspan="3"/>
        <auxheader label="Q2" colspan="3"/>
        <auxheader label="Q3" colspan="3"/>
        <auxheader label="Q4" colspan="3"/>
    </auxhead>
    <columns>
        <column label="Jan"/><column label="Feb"/><column label="Mar"/>
        <column label="Apr"/><column label="May"/><column label="Jun"/>
        <column label="Jul"/><column label="Aug"/><column label="Sep"/>
        <column label="Oct"/><column label="Nov"/><column label="Dec"/>
    </columns>
    <rows>
        <row>
            <label value="1,000"/><label value="1,100"/><label value="1,200"/>
            <label value="1,300"/><label value="1,400"/><label value="1,500"/>
            <label value="1,600"/><label value="1,700"/><label value="1,800"/>
            <label value="1,900"/><label value="2,000"/><label value="2,100"/>
        </row>
        <row>
            <label value="1,500"/><label value="2,100"/><label value="1,200"/>
            <label value="1,100"/><label value="2,400"/><label value="1,700"/>
            <label value="1,500"/><label value="3,700"/><label value="1,800"/>
            <label value="1,300"/><label value="2,000"/><label value="2,500"/>
        </row>
    </rows>
</grid>
    </groupbox>
</zk>




Tuesday, June 18, 2013

How to Drop your file using dropupload in zk




index.zul


<?page title="Auto Generated index.zul"?>
<window title="Drop here" border="normal" width="100%" height="100%"
    apply="org.zkoss.bind.BindComposer"
    viewModel="@id('vm') @init('com.demo.DropFileViewModel')">

    <dropupload maxsize="5120" detection="none"
        onUpload="@command('doUpload')">
    </dropupload>
   
    <button label="Download" onClick="@command('doDownload')"></button>


</window>

DropFileViewModel.java

package com.demo;

import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.util.media.Media;
import org.zkoss.zhtml.Filedownload;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Messagebox;

public class DropFileViewModel {
    Media media;

    @Command
    public void doUpload(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {
        UploadEvent upEvent = null;
        Object objUploadEvent = ctx.getTriggerEvent();
        if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
            upEvent = (UploadEvent) objUploadEvent;
        }
        if (upEvent != null) {
            media = upEvent.getMedia();
            Messagebox.show("File Uploaded: " + media.getName());

        }
    }

    @Command
    public void doDownload() {
        if (media != null)
            Filedownload.save(media);
        else
            Messagebox.show("First Drop Your File");

    }
}

Check online demo here

how to create menu in android

menu.xml
<?xml version="1.0" encoding="utf-8"?>
    <!-- Single menu item
         Set id, icon and Title for each menu item
    -->
    <item android:id="@+id/menu_bookmark"
          android:icon="@drawable/icon_bookmark"
          android:title="Bookmark" />
    <item android:id="@+id/menu_save"
          android:icon="@drawable/icon_save"
          android:title="Save" />
    <item android:id="@+id/menu_search"
          android:icon="@drawable/icon_search"
          android:title="Search" />
    <item android:id="@+id/menu_share"
          android:icon="@drawable/icon_share"
          android:title="Share" />
    <item android:id="@+id/menu_delete"
          android:icon="@drawable/icon_delete"
          android:title="Delete" /> 
    <item android:id="@+id/menu_preferences"
          android:icon="@drawable/icon_preferences"
          android:title="Preferences" />
</menu>


///////////////////////////////

 // Initiating Menu XML file (menu.xml)
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu, menu);
        return true;
    }
     
    /**
     * Event Handling for Individual menu item selected
     * Identify single menu item by it's id
     * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
         
        switch (item.getItemId())
        {
        case R.id.menu_bookmark:
            // Single menu item is selected do something
            // Ex: launching new activity/screen or show alert message
            Toast.makeText(AndroidMenusActivity.this, "Bookmark is Selected", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu_save:
            Toast.makeText(AndroidMenusActivity.this, "Save is Selected", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu_search:
            Toast.makeText(AndroidMenusActivity.this, "Search is Selected", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu_share:
            Toast.makeText(AndroidMenusActivity.this, "Share is Selected", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu_delete:
            Toast.makeText(AndroidMenusActivity.this, "Delete is Selected", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.menu_preferences:
            Toast.makeText(AndroidMenusActivity.this, "Preferences is Selected", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }   
}







































Thursday, June 13, 2013

how to set alt tag in zk

<zk xmlns:ca="client/attribute">

<image src="abc" ca:alt="image not found" ca:title="image title" />

</zk>

how to get after 5 days date

Calendar currentDate = Calendar.getInstance();
        Calendar prevDay = (Calendar) currentDate.clone();
        prevDay.add (Calendar.DAY_OF_YEAR, 5);
        System.out.println ("After 5 Day: " + prevDay.getTime());

How to get previous 7 day Date

Calendar currentDate = Calendar.getInstance();
        Calendar prevDay = (Calendar) currentDate.clone();
        prevDay.add (Calendar.DAY_OF_YEAR, -7);
        System.out.println ("Previous 7 Day: " + prevDay.getTime());

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...