Thursday, 30 June 2011

JDk 1.7 ~String in Switch and Multi Catch~

JDK 1.7 also supports using String in your switch case and multi catch option as shown under.




Swicth case is alternative to your if else condition but only when you need to check for the equality condition(Switch will not support < or > )
When there is choice to be made between if else or switch,its better to opt to switch because of readabilty and fastness in execution (Jump table or Branch table concepts)....thats it for now cheeeers !! ;-)

JDK 1.7 ~java.util.Objects~

Working with Jdk 1.7 early access download,one of the enhancements made is introduction of java.util.Objects similar to that of java.util.Collections.The Objects class supports some null safe and null tolerant methods.Check the following class for some hint.

1.Equals Support



  To know its usefulness let us say your code looks as follows:


     if(foo.equals(foo2)) { //do something }

what if foo is null,you will encounter null pointer exception(else may be you need to have one more check for null),with java.util.Objects


 Objects.equals(foo,foo2)) if foo is null,it will return false :-)






2.Hashing Support:


Most of the standards and technologies need their classed\s to override equals and hashcode method(atleast some times u may need to for better performance e.g. HashMap usage), java.util.objects provides a better way of hashing.



 This is very useful especially for your DTO objects which may contain many number of fields.

 hashCode(Object o):int -->>  Returns the hash code of a non-null argument and 0 for a null argument.


and there is some more enhancements made toString() with null support.

Thats it for now.... cheers ;-)





Tuesday, 28 June 2011

EJP (Easy Java Persistence) (A-ORM)

EJP is relational database persistence API for Java.EJP is far advanced and can handle things automatically,there is no annotation required or the messy xml configurations required as you do in the other type of ORM .But it doesn't support the creation of schema.The perfect scenario for usage of EJP is if you already have the existing database and all you need is to connect to it and work then EJP is perfect choice ;-).

Here you go http://www.easierjava.com/


The following  is the quick sample tried out .


Table  DCT  looks like this: 



The representative java class  for the above DCT table looks as below:



Test Class :


Thats all...Be sure that you have the jar files from the above link in your buildpath and the JDBC driver jar(mysql.jar in my case).EJP can also handle all types of associations and simply called as A-ORM(automatic object/relational mapping) ;-)


Cheers !!! :-)

Spring-JDBCTemplate

The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This helps to avoid common errors such as forgetting to always close the connection.


How to Configure:

Step 1:

Configure the Data source in the xml as below.


<bean  id="DataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
                <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://dxx-3306/test"/>
                <property name="username" value="DurgaPrasad"/>
                <property name="password" value="******"/>
   </bean>


Step 2 :
Inject the  data source to the DAO  bean.Here the dao is DCTDao.


<bean id="DCTDAO" class="com.dct.DAO.DCTDao" >
          <property name="dataSource">
              <ref bean="DataSource" />
          </property>
         </bean> 


Step 3:
 Sample DAO class.

package com.dct.DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

/**
 *
 * @author DurgaPrasad
 *
 * This bean would be injected to the DCTController and this class would take care of the DB interactions.
 * This in turn uses JDBCTemplate to avoid the boiler plate jdbc code.
 *
 */
public class DCTDao {

    String resultString = "";
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    /**
     *
     * @param team
     * @param activity
     * @return
     */
    public int getCount(String team, String activity, String date) {
        return this.jdbcTemplate.queryForInt("select count(*) from dct where team='" + team + "' and ACTIVITY ='" + activity + "' and DEFECT_LOGGED_DATE='" + date + "'");

    }

    /**
     *
     * @param team
     * @param activity
     * @return
     */
    public int getDefectCount(String team, String activity) {
        return this.jdbcTemplate.queryForInt("select DEFECT_COUNT from dct where team='" + team + "' and ACTIVITY ='" + activity + "'");
    }

    /**
     *
     * @param team
     * @param activity
     * @param dCount
     * @param date
     */
    public void createDCT(String team, String activity, int dCount, String date) {
        System.out.println("INSERT into dct values('" + team + "','" + activity + "'," + dCount + ", '" + date + "')");
        this.jdbcTemplate.update("INSERT into dct values('" + team + "','" + activity + "'," + dCount + ", '" + date + "')");
    }

    /**
     *
     * @param team
     * @param activity
     * @param dCount
     * @param date
     */
    public void updateDCT(String team, String activity, int dCount, String date) {
        this.jdbcTemplate.update("update dct set DEFECT_COUNT=" + dCount + " where Team='" + team + "' and DEFECT_LOGGED_DATE='" + date + "' and Activity='" + activity + "'");
    }

    public String getName() {
        return (String) this.jdbcTemplate.queryForObject("select name from DCT", String.class);
    }

    /**
     *
     * @param team
     * @param activity
     * @return
     */
    public String getDefectCountAndDate(String team, String activity, String date) {
        String result = (String) this.jdbcTemplate.query("select DEFECT_COUNT ,DEFECT_LOGGED_DATE from dct where team='" + team + "' and ACTIVITY ='" + activity + "'", new ResultSetExtractor() {
            public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                if (resultSet.next()) {
                    return resultSet.getInt(1) + "|" + resultSet.getString(2);
                }
                return null;
            }
        });
        return result;
    }

    /**
     *
     * @param team
     * @param activity
     * @return
     */
    public int getTotalDefectCount(String team, String activity) {
        return this.jdbcTemplate.queryForInt("select DEFECT_COUNT from dct where team='" + team + "' and ACTIVITY ='" + activity + "'");
    }

    public String getReport(String fromDate, String toDate) {
        System.out.println("select * from dct where  DEFECT_LOGGED_DATE >'" + fromDate + "'and   DEFECT_LOGGED_DATE<'" + toDate + "'");
        resultString = "";
        String result = (String) this.jdbcTemplate.query(" select TEAM,ACTIVITY,DEFECT_COUNT,DEFECT_LOGGED_DATE from dct where  DEFECT_LOGGED_DATE >='" + fromDate + "' and   DEFECT_LOGGED_DATE<='" + toDate + "'", new ResultSetExtractor() {
            public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                while (resultSet.next()) {
                    System.out.println(resultSet.getString(1) + "|" + resultSet.getString(2) + "|" + resultSet.getInt(3) + "|" + resultSet.getString(4));
                    resultString = resultString + resultSet.getString(1) + "|" + resultSet.getString(2) + "|" + resultSet.getInt(3) + "|" + resultSet.getString(4) + "^";

                }
                return resultString;
            }
        });
        return result;
    }
}













This is basic step to configure datasource and injecting the jdbcTemplate.The strring returnedh in some methods here are used with ajax and hence the delimiter stuff I've used,can be still made better based on the purpose.


cheers !! ;-)

 

Monday, 27 June 2011

JMS- Message Broker Apache Active MQ


JMS (Java Messaging Service) API is a java Message Oriented Middleware (MOM) API for communicating between two or more clients. It allows Java components to create, send, receive and read Messages .It allows reliable, loosely coupled, asynchronous communication between various distributed components.

Apache ActiveMQ is an open source message broker which implements the JMS.

Testing ActiveMQ:
-------------------

1.Extract the ActiveMQ
2. Go to the Extracted Folder/bin
3.Run  cmd activemq and on success you should see some thing as in the pic below.



------------------------------------------------------------------------------------------------------------


C:\ActiveMQ5.5\bin>activemq
Java Runtime: Sun Microsystems Inc. 1.6.0_17 C:\Program Files\Java\jdk1.6.0_17\jre
  Heap sizes: current=8896k  free=5824k  max=466048k
    JVM args: -Dcom.sun.management.jmxremote -Xmx512M -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Djava.util.logging.config.file=logging.properties
ACTIVEMQ_HOME: C:\ActiveMQ5.5\bin\..
ACTIVEMQ_BASE: C:\ActiveMQ5.5\bin\..
Loading message broker from: xbean:activemq.xml
 INFO | Refreshing org.apache.activemq.xbean.XBeanBrokerFactory$1@50618d26: startup date [Mon Jun 27 12:32:23 GMT+05:30 2011]; root of context hierarchy
 WARN | destroyApplicationContextOnStop parameter is deprecated, please use shutdown hooks instead
 INFO | PListStore:C:\ActiveMQ5.5\bin\..\data\localhost\tmp_storage started
 INFO | Using Persistence Adapter: KahaDBPersistenceAdapter[C:\ActiveMQ5.5\bin\..\data\kahadb]
 INFO | KahaDB is version 3
 INFO | Recovering from the journal ...
 INFO | Recovery replayed 1 operations from the journal in 0.015 seconds.
 INFO | ActiveMQ 5.5.0 JMS Message Broker (localhost) is starting
 INFO | For help or more information please see: http://activemq.apache.org/
 INFO | Listening for connections at: tcp://D-MAA-00391437:61616
 INFO | Connector openwire Started
 INFO | ActiveMQ JMS Message Broker (localhost, ID:D-MAA-00391437-2490-1309158145193-0:1) started
 INFO | jetty-7.1.6.v20100715
 INFO | ActiveMQ WebConsole initialized.
 INFO | Initializing Spring FrameworkServlet 'dispatcher'
 INFO | ActiveMQ Console at http://0.0.0.0:8161/admin
 INFO | Initializing Spring root WebApplicationContext
 INFO | OSGi environment not detected.
 INFO | Apache Camel 2.7.0 (CamelContext: camel) is starting
 INFO | JMX enabled. Using ManagedManagementStrategy.
 INFO | Found 5 packages with 16 @Converter classes to load
 INFO | Loaded 152 type converters in 0.719 seconds
 INFO | Connector vm://localhost Started
 INFO | Route: route1 started and consuming from: Endpoint[activemq://example.A]
 INFO | Total 1 routes, of which 1 is started.
 INFO | Apache Camel 2.7.0 (CamelContext: camel) started in 1.562 seconds
 INFO | Camel Console at http://0.0.0.0:8161/camel
 INFO | ActiveMQ Web Demos at http://0.0.0.0:8161/demo
 INFO | RESTful file access application at http://0.0.0.0:8161/fileserver
 INFO | Started SelectChannelConnector@0.0.0.0:8161
----------------------------------------------------------------------------------------------------------- 






Monitoring  ActiveMQ:
----------------------- 
ActiveMQ can be monitored on the web console using http://localhost:8161/admin





Sample Producer and Consumer Code:

Note:Add  activemq-all-x.x.x.jar to the build path of the project and start the activemq before you run the sample ;-).

Producer:
package com.activemq.demo;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 *
 * @author DurgaPrasad.K
 *
 */
public class Producer {
    // URL of the JMS server. DEFAULT_BROKER_URL will just mean
    // that JMS server is on localhost
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the queue we will be sending messages to
    private static String subject = "DEMOQUEUE";

    public static void main(String[] args) throws JMSException {
        // Getting JMS connection from the server and starting it
        ConnectionFactory connectionFactory =
            new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // JMS messages are sent and received using a Session. We will
        // create here a non-transactional session object. If you want
        // to use transactions you should set the first parameter to 'true'
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

        // Destination represents here our queue 'DEMOQUEUE' on the
        // JMS server. You don't have to do anything special on the
        // server to create it, it will be created automatically.
        Destination destination = session.createQueue(subject);

        // MessageProducer is used for sending messages (as opposed
        // to MessageConsumer which is used for receiving them)
        MessageProducer producer = session.createProducer(destination);

        // We will send a small text message saying 'ActiveMQ Demo'
        TextMessage message = session.createTextMessage("ActiveMQ Demo");

        // Here we are sending the message!
        producer.send(message);
        System.out.println("Sent message '" + message.getText() + "'");

        connection.close();
    }
}


Consumer : 


package com.activemq.demo;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer {
    // URL of the JMS server
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    // Name of the queue we will receive messages from
    private static String subject = "DEMOQUEUE";

    public static void main(String[] args) throws JMSException {
        // Getting JMS connection from the server
        ConnectionFactory connectionFactory
            = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        // Creating session for seding messages
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

        // Getting the queue 'TESTQUEUE'
        Destination destination = session.createQueue(subject);

        // MessageConsumer is used for receiving (consuming) messages
        MessageConsumer consumer = session.createConsumer(destination);

        // Here we receive the message.
        // By default this call is blocking, which means it will wait
        // for a message to arrive on the queue.
        Message message = consumer.receive();

        // There are many types of Message and TextMessage
        // is just one of them. Producer sent us a TextMessage
        // so we must cast to it to get access to its .getText()
        // method.
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message '"
                + textMessage.getText() + "'");
        }
        connection.close();
    }
}
 












Cheers !! ;-) 


Thursday, 23 June 2011

Add New Rows Dynamically with a Del button for each row using JS


 The below image would explain what the following code does.This  is done at the time I started learning  js can be still made better.


<html>
  <head>
<script>
                   function startAdd()
                   {
                   var tbl = document.getElementById("sample1");
                   row =tbl.insertRow();
                   var td=document.createElement("TD");
                   var elem=    document.createElement("<input name='text1' value='ee'   type='text'  size='5' />");
                   td.appendChild(elem);
                   var elem0=    document.getElementById('sampleDd');
                   td.innerHTML=td.innerHTML+document.getElementById('sampleDd').innerHTML;
                   var elem1=    document.createElement("<input type='text' value='sample' size='5' />");
                   td.appendChild(elem1);
                   var elem2=    document.createElement("<input type='text' value='sample' size='5' />");
                  td.appendChild(elem2);
                  var elem3=    document.createElement("<input type='button' value='delete' size='5' onClick=removeRow('sample1') />");
                  td.appendChild(elem3);
                  row.appendChild(td);
               }
        function removeRow(tableName)
        {
            row=event.srcElement.parentNode.parentNode;
            document.all[tableName].deleteRow(row.rowIndex);
        }
                       function traceChange(obj)
                       {
            row=event.srcElement.parentNode.parentNode.parentNode;
                              document.getElementsByName("text1")[row.rowIndex-2].value="sample";
                        }
                     </script>   
            </head>
             <body>
                <form name="jsform">
          <table id="sample1">
          <tr>
                       <td><input type=button  value="add" onClick="startAdd()"></td>

           </tr>
                   <tr style="display:none;">
             <td  id="sampleDd">
        <nobr>
         
          <select name="sel" onChange="traceChange(this)" value="one"><option>1</option>
          <option value="two">2</option>
                  <option value="three">3</option>

                  <option value="four">4</option></select>
        </nobr>
          </td>
</tr>
</table>
</form>
</body>
</html>




Cheers :-)

Expand Collapse Tree structure using js and jquery

The following code illustrates the creation of tree expand and collapse using js and jquery.The input passed here is through the xml.


<html>
    <head>
        <title> Sample Tree Structure</title>
        <script type="text/javascript" src="jquery-1.2.6.js"> </script>
        <script>
            var XMLDoc = new ActiveXObject("Microsoft.XMLDOM");
            XMLDoc.load("College.xml");

            function makeTree(){
                var classNode=XMLDoc.getElementsByTagName("class1");
                alert(classNode.length);
                var treeElement=document.getElementById("treeDiv");
                var rowId  = treeElement.rows.length;
                var tr     = treeElement.insertRow(rowId)
                var td = tr.insertCell();

                for(var i=0;i<classNode.length;i++){
                    for(var j=0;j<classNode[i].childNodes.length;j++){
                        var rowId  = treeElement.rows.length;
                        var tr     = treeElement.insertRow(rowId)
                        var td = tr.insertCell();
                        if(j==0){
                            if(classNode[i].childNodes.length>1)
                                td.innerHTML="<li><B><img src='colapse.GIF' onClick='showChildElements(this)'>"+classNode[i].childNodes[j].text+"</B>"
                            else
                                td.innerHTML="<li><B>"+classNode[i].childNodes[j].text+"</B>"


                        }
                        else{
                            td.innerHTML="<span class='dummy' style='display:none'><li>"+classNode[i].childNodes[j].text+"</span>"
                            td.se
                            td.align="center";
                        }
                    }
                }

            }

            function showChildElements(obj){

                if($(".dummy").css("display")=='none'){
                    $(".dummy").css("display","block");
                    obj.src="exp.gif";
                }
                else
                {
                    $(".dummy").css("display","none");
                    obj.src="colapse.gif";
                }

            }

        </script>
    </head>
    <body onLoad="makeTree()">
        <table id="treeDiv" border=1 width="8%">
        </table>
    </body>
</html>



Sample XML:
----------------

<?xml version="1.0" ?>
   <College>
         <class1>
                 <course>
                      java
                  </course>
                 <subcourse>j2ee</subcourse>
                 <subcourse>jmx</subcourse>
                 <subcourse>jsp</subcourse>

        </class1>
   </College>
 


The XMLDOM  I'm using is in particular to I.E  and  also the js can be totally replaced with jquery.excuse me for styles and formattings.


Cheers !! ;-) 

Lock - java.util.concurrent.locks


java.util.concurrent.locks
Interface - Lock

All Known Implementing Classes:
ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock .






The java.util.concurrent.locks package has a standard Lock interface. The ReentrantLock implementation duplicates the functionality of the synchronized keyword but also provides additional functionality such as obtaining information about the state of the lock, non-blocking tryLock(), and interruptible
locking
While the scoping mechanism for synchronized  methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

Example of using an explicit ReentrantLock instance:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author DurgaPrasad
 *
 */
public class ReentrantLockDemo {
    int counter=0;
   private final Lock lock = new ReentrantLock();
    public void getData(){
        lock.lock();
        try{
           
        }
        finally{
            lock.unlock();
        }
       
    }
}



The java.util.concurrent.locks package also containsa ReadWriteLock interface (and ReentrantReadWriteLock implementation) which is defined by a pair of locks forreading and writing, typically allowing multiple concurrent readers but only one writer. Example of using an explicit ReentrantReadWriteLock to allow multiple concurrent readers:.

public class Statistic {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private int value;
public void increment() {
lock.writeLock().lock();
try {
value++;
} finally {
lock.writeLock().unlock();
}
}
public int current() {
lock.readLock().lock();
try {
return value;
} finally {
lock.readLock().unlock();
}
}
}



Cheers !! :-)

JS Compression

Have you ever opened the jquery.js.Do you think its readable or a human coded file.Its absoluetly no. why the heck it is like that?


If you dont agree see the below line of code and try understanding it.


(function(a,b){function cg(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cd(a){if(!bZ[a]){var b=d("<"+a+">").appendTo("body")

 This loss of readability is to decrease the byte foot print and anyways readability is not a matter to be considered in the prod environment. 

Sample Hand written JS Code  :
function submitForm(){
 var myOBJ=document.getElementById("dummy");
 var value=myOBJ.value();
 alert(value);
 document.getElementsByName("MFW_LOGIN_FORM")[0].submit();
}


 Minified Code:

 function submitForm(){
var a=document.getElementById("dummy"),b=a.value();alert(b),document.getElementsByName("MFW_LOGIN_FORM")[0].submit()}  

 Ugly version:

        Old version:  174 bytes
        New version: 139 bytes
        Saved: 35 (result is 79.8% of original)  

There are lot of tools available for this JS compression and for instance I'm using UglifyJS... Hope this will be useful when you have lot of js... ;-) cheers !!! 


Wednesday, 22 June 2011

JunitDoclet



To better understand the reflection api , I was using java.lang.reflect.* for creation of  junit skeleton on the go and later discovered there is a similar stuff which creates the junit structure and the suites for the specified package called JUNITDOCLET.

Following is the build.xml used for creation of junit classes and the suites for the classes under package com.abc.dummy and can be specified as com.abc.*.It takes care of all the lifecycle methods of junit. This JunitDoclet is most handy when the classes have more number of method and it supports 3.x and 4.x versions of junit depending on the Junitdoclet jar in the buildpath ;-)



<?xml version="1.0" encoding="UTF-8"?>
<project name="Dummy" default="junittest" basedir=".">
<description>
simple example build file for JunitDoclet task
    </description>
<!-- set global properties for this build -->
<property name="src" location="src" />
<property name="build" location="build" />
<property name="dist" location="dist" />
<property name="lib.dir" value="lib" />
<property name="junit1" value="./junit1" />
<property name="classes" value="${build}/classes" />
<property name="package" value="com.abc.dummy" />
<property name="testsuite" value="${package}.DummySuite" />
<path id="classpath_default">
<pathelement path="${classes}" />
<!-- the javadoc classes are in this package -->
<pathelement path="${java.home}/../lib/tools.jar" />
<fileset dir="${lib.dir}">
<include name="junit-4.8.1.jar" />
<include name="junitdoclet-1.6.jar" />
</fileset>
</path>
<target name="init">
<!-- Create the time stamp -->
<tstamp />
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}" />
</target>

<target name="compile" depends="init" description="compile the source ">
<echo message="=============Compiling================" />
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}">
<classpath>
<pathelement location="${lib.dir}/" />
<pathelement location="${lib.dir}/junit-4.8.1.jar" />
</classpath>
</javac>
<echo message="=============Compiling Completed================" />
</target>
<target name="junitdoclet" depends="compile">
<echo message="=============JUNIT DOCLET STARTED================" />
<javadoc packagenames="com.abc.dummy" sourcepath="${src}"
defaultexcludes="yes" doclet="com.objectfab.tools.junitdoclet.JUnitDoclet"
docletpathref="classpath_default" additionalparam="-d ${junit1} -buildall">
<classpath refid="classpath_default" />
</javadoc>
<echo message="=============JUNIT DOCLET COMPLETED================" />
<echo message="${testsuite}"></echo>
</target>

<target name="junitcompile" depends="junitdoclet">
<javac srcdir="${junit1}" destdir="${classes}" debug="on">
<classpath refid="classpath_default" />
</javac>
</target>
<echo message="----------------------------------------------"/>
<echo message="${classpath_default}"/>
<echo message="----------------------------------------------"/>
<target name="junittest" depends="junitcompile">
<junit fork="yes" haltonfailure="no">
<formatter type="plain" />
<test name="${testsuite}" outfile="testresults" />

<classpath refid="classpath_default" />
</junit>
</target>
</project>

Simple Quiz


Problem

Back in the old days before the creation of the mighty Centauri Republic, the planet Centauri Prime was split into several independent kingdoms. The kingdom of Mollaristan was ruled by king Loatold, while the kingdom of Auritania was under the rule of queen Elana. In fact, it just so happened that every kingdom whose name ended in a consonant was ruled by a king, while every kingdom whose name ended in a vowel was ruled by a queen. Also because of an amazing coincidence, all kingdoms whose named ended in the letter 'y' were constantly in a state of turmoil and were not ruled by anyone. Can you write a program that will determine the current rulers of several countries, given the countries' names?

Input

The first line of the input gives the number of test cases, TT lines follow, each one containing the name of one country. Country names will consist of only lower case English letters, starting with a capital letter. There will be no other characters on any line, and no empty lines.

Output

For each test case, output one line containing "Case #xC is ruled by Y.", where x is the case number (starting from 1), C is the country name, and Y is either "a king", "a queen" or "nobody".





Code:


package com.quiz.sample;


import java.util.Scanner;


/**
 * 
 * @author DurgaPrasad
 *
 */
public class VowelConsonent {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter the number of testcases");
int num =scan.nextInt();
for(int i=1;i<=num+1;i++){
System.out.println("enter the name");
String name=scan.next();
String last=name.substring(name.length()-1);
if(last.equals("y")){
System.out.println("case :"+i+" " +name+" "+"is ruled by NO Ruler");
}
else if("aeiou".contains(last)){
System.out.println("case :"+i+" "+name+" "+"is ruled by queen");
}else{
System.out.println("case :"+i+" "+name+" "+"is ruled by king");
}
}
}
}


JS Drag and Drop for I.E


The following Code (Initial Version)illustrates the drag and drop using JS(for I.E )to drop zone(table here).I'm using the x and y co-ordinates to trigger the drop event..so can be integrated with ajax for further process(can be some db persistence.)


<html>
<head>
<style>
.drago{position:relative;cursor:hand}
</style>
<script >

var dragapproved=false
var z,x,y
function move(){
if (event.button==1&&dragapproved){
z.style.pixelLeft=temp1+event.clientX-x
z.style.pixelTop=temp2+event.clientY-y
return false
}
}
function drags(){
if (!document.all)
return
if (event.srcElement.className=="drago"){
dragapproved=true
z=event.srcElement
temp1=z.style.pixelLeft
temp2=z.style.pixelTop
x=event.clientX
y=event.clientY
document.onmousemove=move
}
}
document.onmousedown=drags
document.onmouseup=Trigger;
//-->

function Trigger(){
dragapproved=false
var x=event.clientX
var y=event.clientY
if(x>=12 && x<=319){
if(y>=77 && y<=124){
alert(event.srcElement.id +" placed on drop zone...call Ajax");
}
}
}
function display(){
x=event.clientX
y=event.clientY
document.getElementById("disp").innerHTML=x+":"+y;
}
</script>
</head>
<body>
<img src="sun1.png" id="pic1" class="drago"><br>
<img src="sun2.png" id="pic2" class="drago"><br>
<label class="drago" id="lbl">sample</label>
<table border=1 width="25%" onmouseover="display()">
<tr><td>&nbsp;</td></tr>
</table>
<div id="disp">
</div>
</body>
</html>





excuse me for styles and formating ;-)