Monday, January 7, 2013

Quercus Run PHP on Java (JVM) as template engine


Quercus project help easy run php on JVM

To run Quercus  you can download  file resin.jar on  http://quercus.caucho.com/

However i extract only 3 file (small than one resin.jar which have a ton of jars flie)


http://commondatastorage.googleapis.com/static.i-php.net/lib.zip


Have many way php on java , but i will using  "Scripting Java" to run .

"Scripting Java" is interface can run any scripting language if have interpreter or compiler

Demo



QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
engine.put("abc", "def");
ScriptContext context = engine.getContext();
try {
engine.eval("<h1>hello   <?=$abc?>  </h1>");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Tuesday, June 5, 2012

Begining HTML5 game part 3

To continue "Begining HTML5 game part 2" :

Today, we build and play BlackJack game.

In js folder, create player.js file : contain methods of player interactive with cards and computer
var Player = function(name)
{
      this.cards = [];
      this.x=400; //position for cards
      this.y=300;
      this.calcPoint=function()// calculate point of player
     {
            var total =0;
            for ( var i = 0; i < this.cards.length; i++) 
            {
                    total+=this.cards[i].value;
                      
            }
            return total;
     }
     
     this.draw = function(graphic) // draw cards of player
     {
           for ( var i = 0; i < this.cards.length; i++) 
          {
                 this.cards[i].x=this.x+i*21; // set distance between 2 cards
                 this.cards[i].y=this.y;
                 this.cards[i].draw(graphic);
          }
              
     }
}
In js folder, create computer.js, extends player.js file
          var Computer =  function()
          {
                 this.x=400;
                 this.y=80;

           }
Computer.prototype =new Player(); //computer extends player
In dealer.js, define deal function to deal cards to player and computer :
//deal card
this.deal = function(step)
{
      if(step==5) return ;
      var card1 = this.cards.pop();
      if(step!=4)
      {
            card1.flip();
      }
      if(step==1||step==3)
      {
            this.player.cards.push(card1);
      }
      if(step==2||step==4)
      {
            this.computer.cards.push(card1);
      }
      setTimeout("dealer.deal("+(step+1)+")",1000);
}
In index.html, in head section, add :
        //set border for layout of canvas tag by 1px solid and has black colour
s<style type="text/css">
        canvas {
               border: 1px solid black;
        }
</style>
index.html-> head section -> <script> tag : add code to init player and computer and assign to player and computer:
var dealer = new Dealer();
var player = new Player();
var computer = new Computer();
dealer.player=player;
dealer.computer=computer;

index.html -> body section : add deal button :
<input type = "button" id = "dealId" name = "dealBtn" value = "Deal" onclick="dealCard()"></input>
index.html -> head section -> <script> tag : create dealCard function to handle event when player click "Deal" button.
function dealCard()
{
       dealer.deal(1);
}

To create Hit Button :
index.html -> body section -> add Hit button :
<input type = "button" id = "hitId" name = "hitBtn" value = "Hit" onclick="hit()"></input>
 index.html -> head section -> script tag : define hit function to player and computer :
function hit()
{
       player.hit();
       computer.hit();
 And same dealCard function, you need init and assign to player and computer when they hit in index.html->head section -> script tag :
player.dealer = dealer;
Computer.dealer = dealer;
In computer.js file, define hit function for computer:
           this.hit = function()
           {
                  dealer.computerHit();
In player.js file, define hit function for player:
           this.hit = function()
           {
                  dealer.playerHit();
In dealer.js, create hit fuction for player and computer :
          this.playerHit = function()
         {
                var card = this.cards.pop();
                this.player.cards.push(card);
                card.flip();
         }
         this.computerHit = function()
         {
               var card = this.cards.pop();
               this.computer.cards[this.computer.cards.length-1].flip();
               this.computer.cards.push(card);

Result :
  
Now, we create more Stand and Repeat button in index.html
<input type = "button" id = "standId" name = "standBtn" value = "Stand" onclick="stand()"></input>
   
   
    <input type = "button" id = "repeatId" name = "repeatBtn" value = "Repeat" onclick="repeat()"></input>

And index.html->head section -> script section : define 2 functions for stand() and repeat() for player when player choose stand button or repeat button.
 function stand()
 {
        player.stand();
 }  
   
 function repeat()
 {
        player.repeat();
 }

In Player.js : define methods stand() and repeat()
     this.stand = function()
    {
        if(this.calcPoint()<21)
        {
            dealer.playerStand();
        }
    }
   
    this.repeat = function()
    {
        dealer.playerRepeat();
    }

In dealer.js : define methods playerStand() and playerRepeat() and checkPoint() to check Point of Player and Computer

     this.checkPoint = function()
    {
        var cPoint = 0;
        var pPoint=0;
        cPoint = computer.calcPoint();
        pPoint = player.calcPoint();
        //alert("point of computer : "+computer.calcPoint());
       
        if(actionStr=="playerHit")
        {
           
            if(pPoint>21)
            {
                alert("You lose");
                return;
            }
            if(pPoint<21)
            {
               
                if(cPoint==pPoint)
                {
                    alert("You draw");
                    return;
                }
                if(cPoint>21)
                {
                    alert("You win");
                    return;
                }
                if(pPoint==21)
                {
                    alert("You win");
                    return;
                }
            }
            if(pPoint==21)
            {
                if(pPoint==cPoint)
                {
                    alert("You draw");
                    return;
                }
                if(pPoint>cPoint)
                {
                    alert("You win");
                }
            }
           
        }
        else if(actionStr=="playerStand")
        {
            if(cPoint<=21)
            {
               
                if(cPoint>pPoint)
                {
                    alert("You lose");
                    return;
                }
                if(cPoint<pPoint)
                {
                    alert("You win");
                    return;
                }
                if(cPoint==pPoint)
                {
                    alert("You draw");
                    return;
                }
            }
            else
            {
                alert("You win");
                return;
            }
        }
       
    }
     this.playerStand = function()
    {
        actionStr="playerStand";
        this.computer.cards[this.computer.cards.length-1].flip();
        this.checkPoint();
      
    }
   
    this.playerRepeat = function()
    {
      
        while(this.player.cards.length>0)
        {
            var card = this.player.cards.pop();
            this.cards.push(card);
            card.flip();
            card.x = this.x;
            card.y = this.y;
        }
      
        
        while(this.computer.cards.length>0)
        {
            var card = this.computer.cards.pop();
            this.cards.push(card);
            card.flip();
            card.x = this.x;
            card.y = this.y;
        }
      

        this.shuffle();//recall shuffle() method to shuffle cards.
      
    }

Result:

It's demo. To better, you need set rate and blackjack game rule to exactly.

Full Source code : https://docs.google.com/open?id=0Bw97UupVaNHuYUpnWkpCc1J2bHc

Hope to helping ^^
Part 1
Part 2

Tuesday, May 29, 2012

Begining HTML5 game part 2

To continue Begining HTML5 game part 1 .

Download images for this tutorial .

https://docs.google.com/open?id=0B3wmdk4k7b_-V3Q1TTVIWW5LaWM (Save s to get zip package)

We using simple html5 game framework for develop a card game . Maybe blackjack

First, you need create Struct Folder to easy manager when your project become  complex 


In WebContent-> index.html :
Body part, add code into body of index.html file
<canvas id="gameCanvas" width="800"  height="550">

</canvas>
Body tag : add code into body tag :
<body onload="initGame()">
Head-> add Script tag : define 3 methods  into <script></script> tag :
function draw()
function initGame()
function update()
 index.html -> draw function : add more code :
update();
 requestAnimFrame(draw);
In js folder, create util.js file : contain some util functions and call util.js in index.html
window.requestAnimFrame = (function(){
   return  window.requestAnimationFrame       ||
           window.webkitRequestAnimationFrame ||
           window.mozRequestAnimationFrame    ||
           window.oRequestAnimationFrame      ||
           window.msRequestAnimationFrame     ||
           function( callback ){
             window.setTimeout(callback, 1000 / 60);
           };
 })();

 In js folder, create card.js file : description about card object : set name , set value, draw for a card
In js folder, create dealer.js file :init for 52 cards

In index.html  : add more code in draw function           
        var gameCanvas = document.getElementById("gameCanvas");
        var graphic =  gameCanvas.getContext('2d');
and include 2 file :  card.js and dealer.js to script tag.


To test, i'll add more code to flip card when i click on card

Add flip function to card.js
this.flip=function()
       {
               if(this.status==0)
               {
                       this.status=1;
               }
               else
               {
                       this.status=0;
               }
       }
Call shuffle() function of util.js in card.js to shuffle cards.
shuffle(this.cards);
 Create position and draw cards in card.js
for ( var i = 0; i < this.cards.length; i++) {
                    
           t=parseInt(i/15)*4;
           
           // no animation
         
           this.cards[i].x=this.x+t;
           this.cards[i].y=this.y;
          
                    
           }
   
    this.draw = function(graphic)
    {
        for ( var i = 0; i < this.cards.length; i++)
        {
           
            this.cards[i].draw(graphic);
        }
             
    }
 In index.html : Add canvasClicked function to <script> tag of <head> tag to handle event
function canvasClicked(e)
{
    var gameCanvas = document.getElementById("gameCanvas");
    var x;
    var y;
    if (e.pageX || e.pageY) {
      x = e.pageX;
      y = e.pageY;
    }
    else {
      x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    x -= gameCanvas.offsetLeft;
    y -= gameCanvas.offsetTop;
    for ( var i = 0; i < dealer.cards.length; i++) {
              
           
            if((dealer.cards[i].x<x) &&(dealer.cards[i].x+90>x) && (dealer.cards[i].y<y) &&(dealer.cards[i].y+135>y)  )
            {
                dealer.cards[i].flip();
                   
            }
           
              
              
    }
   
}
and add more code in initGame function :
//listener event click
 var gameCanvas = document.getElementById("gameCanvas");
  gameCanvas.addEventListener("click",canvasClicked,true);
Declare and init value for dealer :
var dealer = new Dealer();
And draw cards in draw function
dealer.draw(graphic);
Result : Drew cards and when you click to card, card will be flip.
Source code :  https://docs.google.com/open?id=0Bw97UupVaNHuVDVIZ1ZOQ21hQWc

Part 1
Part 3

Monday, May 28, 2012


Create slick effects with CSS3 box-shadow


Drop shadows and inner shadows are some of the effects I learned to apply using Photoshop’s Blending options. But now, since CSS3 “hit the charts”, you don’t need Adobe’s design tool to add a drop shadow or an inner shadow to a box. 


Nowadays, the cool thing is that you create beautiful CSS3 shadows without actually needing Photoshop anymore. 

Browser Support



  • Internet Explorer 9/10

  • Firefox (from 3.5)

  • Safari/Chrome

  • Opera (from 10.5)


Add below Style in Header section :  





<style>

    html, body

    {

        height: 100%;

        margin: 0;

        padding: 0;

    }

  

    body

    {

        background: #b3b4b7;

        text-align: center;

    } 

  

    h1

    {

      font-family: 'Allan', serif;

      text-shadow: 0 1px 0 rgba(255,255,255,.5);

      margin: 20px 0;

    }



    /* --------------------------- */

  

    body:before

    {

      content: "";

      position: fixed;

      top: -10px;

      left: 0;

      width: 100%;

      height: 10px;

      z-index: 100;

      -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,.8);

      -moz-box-shadow: 0px 0px 10px rgba(0,0,0,.8);

      box-shadow: 0px 0px 10px rgba(0,0,0,.8);           

    }



    /* --------------------------- */

  

    #box

    {

      position: relative;

      width: 60%;

      background: #ddd;

      -moz-border-radius: 4px;

      border-radius: 4px;

      padding: 2em 1.5em;

      color: rgba(0,0,0, .8);

      text-shadow: 0 1px 0 #fff;

      line-height: 1.5;

      margin: 60px auto;

    }





    #box:before, #box:after

    {

      z-index: -1;

      position: absolute;

      content: "";

      bottom: 15px;

      left: 10px;

      width: 50%;

      top: 80%;

      max-width:300px;

      background: rgba(0, 0, 0, 0.7);

      -webkit-box-shadow: 0 15px 10px #000000(0,0,0, 0.7); 

      -moz-box-shadow: 0 15px 10px  #000000 (0, 0, 0, 0.7);

      box-shadow: 0 15px 10px  #000000 (0, 0, 0, 0.7);

      -webkit-transform: rotate(-3deg);  

      -moz-transform: rotate(-3deg); 

      -o-transform: rotate(-3deg);

      -ms-transform: rotate(-3deg);

      transform: rotate(-3deg);

    }

    #box:after

    {

      -webkit-transform: rotate(3deg);

      -moz-transform: rotate(3deg);

      -o-transform: rotate(3deg);

      -ms-transform: rotate(3deg);

      transform: rotate(3deg);

      right: 10px;

      left: auto;

    }  

</style>
Add below html in body section :  


<div id="box">

<h1>Lorem ipsum dolor sit amet</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sapien elit, pulvinar a fermentum vel,

sagittis nec dolor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>

</div> 

Friday, May 25, 2012

WebServerSocket with JWebSocket in Java

First, go to http://jwebsocket.org/ to Download 2 package Server and Client . If you want to view Source, plz download source package.
  1. Server
    1. Unzip Server package.
    2. Go to "conf" folder
    3. Choose "jWebSocket.xml" file to open
    4. Edit  "jWebSocket.xml" file, add more couple of tag  <domain>null</domain> in couple of tag <domains> <domains>
    5. Save "jWebSocket.xml" file.
    6. Turn on Terminal,  run Server
      1. Go to server folder contain "/bin/"
      2. type : input command to terminal
        1. For mac or Ubuntu: sh jWebSocketServer.sh 
        2. For win : jWebSocketServer.bat
  2. Client :

    1. Unzip Client package.
    2. Run "index.html" file on browser.
    3. Choose Chat to test. Account login : you can find account Login in "jWebSocket.xml" file of Server Package. Login with each account in 2 windows others
      1. username1 : guest - password1 : guest
      2. username2 : user - password2 : user
  3. Result Testing Chat :
 Done ^^

Begining HTML5 game part 1

OK. Let's start .

Do you know HTML ?
Create file game.html with content :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

</body>
</html>
Adding some javascript as framework

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
    function update()
    {
        // Game UPDATE login
    }
    function draw()
    {
        // game DRAW
      
    }
    function setup()
    {
      
        setInterval(draw, 21);
        setInterval(update, 21);
    }
</script>
</head>
<body onload="setup()">
    <canvas id="gameCanvas" width="800"  height="550">

</canvas>
</body>
</html>

You can see a HTML5 Canvas tag . We will create game , and draw all thing on this canvas
function setup  some variables and create game loop .

Now we will addling some object to game . A image may be good for begin .
I will draw this image on canvas :



you can download and reset name for image is "monday.jpg" in same location of html file
  function draw()
    {
        // game DRAW
        var gameCanvas = document.getElementById("gameCanvas");
        var graphic =  gameCanvas.getContext('2d');
        var monday = new Image();
                 // you can download and reset name for image is "monday.jpg"
        monday.src="monday.jpg";
         graphic.drawImage(monday,100, 100);
       
    }
 Open browser and you can see this image show on canvas .

OK.  For now we implement simple event mouse event .
function setup()
    {
        var gameCanvas= document.getElementById("gameCanvas");
        gameCanvas.addEventListener("click", canvasClicked,true);
        //setInterval(draw, 21);
        setInterval(update, 21);
       
    }
    function canvasClicked(e)
    {
       
        var gameCanvas = document.getElementById("gameCanvas");
        var graphic =  gameCanvas.getContext('2d');
        var monday = new Image();
        monday.src="monday.jpg";
         graphic.drawImage(monday,e.clientX, e.clientY);
       
    }

Function draw is not loop (commented //setInterval function call), to you can see when click to canvas , new Image is drawn.

As you see HTML5 not so hard as you think , it very simple .

Result : when you click mouse, you could see  monday.jpg draw :D



Full source

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
    function update()
    {
        // Game UPDATE login
    }
    function draw()
    {
        // game DRAW
        var gameCanvas = document.getElementById("gameCanvas");
        var graphic =  gameCanvas.getContext('2d');
        var monday = new Image();
        monday.src="monday.jpg";
         graphic.drawImage(monday,100, 100);
       
    }
    function setup()
    {
        var gameCanvas= document.getElementById("gameCanvas");
        gameCanvas.addEventListener("click", canvasClicked,true);
        //setInterval(draw, 21);
        setInterval(update, 21);
       
    }
    function canvasClicked(e)
    {
       
        var gameCanvas = document.getElementById("gameCanvas");
        var graphic =  gameCanvas.getContext('2d');
        var monday = new Image();
        monday.src="monday.jpg";
         graphic.drawImage(monday,e.clientX, e.clientY);
       
    }
</script>
</head>
<body onload="setup()">
    <canvas id="gameCanvas" width="800"  height="550">

</canvas>
</body>
</html>


 part 2 is for next post .
Part 3





Thursday, May 24, 2012

Task Queues in google app engine

Normal, when you crawl data, at the time, you need send a request to crawl, sequential. And wait  webpage to response result. if you have to do this working more several times, you need to care their result and it takes a long time to response these working done . To Resolve these problems, We use Task Queues. We only list our working to resolve. It work automatic and you don't care how to long time it's done. Example, when you resgister on a forum, you don't wait webpage send email to complete register proccessing, you can view immediate these topics of forum.


First, create queue.xml file in WEB-INF has content :

<queue-entries>
<!–Change the refresh rate of the default queue to 1/s–>
<queue>
<name>default</name>  //name of  task queue will call in servlet
<rate>100/s</rate>  //several times use task queues in 1s
</queue>
</queue-entries>

create 1 servlet to add task queues(DemoServlet.java)

package Showsiteinfo.cron;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.*;
@SuppressWarnings(“serial”)
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType(“text/html”);
resp.setCharacterEncoding(“utf-8″);
for(int i=0;i<100;i++)
{
Queue queue = QueueFactory.getDefaultQueue();  //call default task queues was config in queue.xml file.
queue.add(withUrl(“/queue”).method(Method.GET).param(“name”, “abc”));  // call url queue to use method get with parameter name=abc
}
}
}

Go to web.xml to edit path DemoServlet.java is "/demo"
Now, we run link "/demo", so, 1s(maybe more 1s), we did 100 request to url/queue.
 Limit of Google : don't allow to us call links from a domain or other app, so only call in itself in app that you are do task queues.