Monday, May 4, 2015

Symfony

Step 1
Set the path to project folder in the command prompt

Step 2
Type the following command
            Php app/console server:run

Step 3
Create Entity folder in the demobundle à project/project1/src/Acme/DemoBundle
In the Entity folder, create new file à Person.php ( contains attributes, asserts, getter and setters )

Person.php


<?php
namespace Acme\DemoBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;

class Person
{

 /**
  *@Assert\NotBlank()
  *@Assert\Email()
 */
 protected $email;

 /**
  *@Assert\NotBlank()
 */
 protected $fullname;


 public function getEmail()
 {
  return $this -> email;
 }
 public function setEmail($email)
 {
  $this-> email = $email;
 }
 public function getFullname()
 {
  return $this->fullname;
 }
 public function setFullname($fullname)
 {
  $this-> fullname = $fullname;
 }
}

?>


Step 4

Create php file in Acme/Demobundle/Form as PersonType.php.
In here we create the form to be appeared on the browser


PersonType.php


<?php
Namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;


class PersonType extends AbstractType
{

 Public function buildForm(FormBuilderInterface $builder, array $options)
 {
  $builder -> add('email','email')->add('fullname','text')->add('submit','submit');
 }

 Public function getName()
 {
  return 'person';
 }
}






Step 5

We modify the twig.
Demobundle à resources à views à welcome folder à index.html.twig

Remove all the <div> blocks and contents within them.


Index.html.twig

{% extends 'AcmeDemoBundle::layout.html.twig' %}

{% block title %}Symfony - Welcome{% endblock %}

{% block content_header '' %}

{% block content %}
    {% set version = constant('Symfony\\Component\\HttpKernel\\Kernel::MAJOR_VERSION') ~ '.' ~ constant('Symfony\\Component\\HttpKernel\\Kernel::MINOR_VERSION')%}

    <h1 class="title">Welcome!</h1>

    <p>Congratulations! You have successfully installed a new Symfony application.</p>
 
 {{form_start(form , {attr : {novalidate:'novalidate'}})}}
 {{form_row(form.email)}}
 {{form_row(form.fullname)}}
 {{form_end(form)}}
 
{% endblock %}


Step 6

We modify the WelcomeController
Demobundle à controller à WelcomeController



welcomController.php


<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Acme\DemoBundle\Entity\Person;
use Acme\DemoBundle\Form\PersonType;
use Symfony\Component\HttpFoundation\Response;


class WelcomeController extends Controller
{
    public function indexAction()
    {
        /*
         * The action's view can be rendered using render() method
         * or @Template annotation as demonstrated in DemoController.
         *
         */
   
   //$user=array('name'=>'Nimal','active'=>true);
   
   $person = new Person();
   $form = $this->createForm(new PersonType(),$person);
   
   
  $request = $this->get('request');
  $form-> handleRequest($request);
  if($request->getMethod() == 'POST')
  {
   if($form -> isValid())
   {
    return new Response('Person Created');
   }
   else
   {
    return new Response('Error Occured while creating Person');
   }
   
  
   //return $this->render(‘AcmeDemoBundle:Main:index.html.twig’, array[‘form’=>$form=>createView()]);
   

  
  }
 
  return $this->render('AcmeDemoBundle:Welcome:index.html.twig' , array('form'=>$form->createView()));

 }
}





PHP Basics

Basic PHP Lab
Student.html

<html>
<head>
<title> Student Registration Form </title>
</head>
<body>
<center>
<h4>
<form name = "Student Form" method= "POST" action= "display.php">
<table>
<caption><h3>Student Registration Form</h3></caption>
<tr>
<td>Registration number</td>
<td><input type = "text" name="regNo"/></td>
</tr>
<tr>
<td>Student name</td>
<td><input type = "text" name="StdName"/></td>
</tr>
<tr>
<td>Student email</td>
<td><input type = "text" name="email"/></td>
</tr>
<tr>
<td>Student year:</td>
<td><input type = "radio" value="yr3" name="year"/>year 3
<input type = "radio" value="yr4" name="year"/>year 4
</td>
</tr>
<tr>
<td><select name="course">
<option value = "IT">IT</option>
<option value = "BM">BM</option>
<option value = "Engineering">Engineering</option>
</select>
</td>
</tr>
<tr>
<td colspan = "2"><input type="submit" value="insert" name="insert"/>
<input type="submit" value="update" name="update"/>
<input type="submit" value="delete" name="delete"/>
<input type="submit" value="view" name="view"/>
<input type="submit" value="reset" name="reset"/>
</td>
</tr>
</table>
</form>
</h4>
</center>
</body>
</html>
</table>
</h4>
</center>
</body>
</html>



Display.php

<?php
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$mysql_db = "Student";
if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !mysql_select_db($mysql_db)) {
die(mysql_error());
}

?>

<?php

if(isset($_POST["regNo"]) && isset($_POST["StdName"]) && isset($_POST["email"]) && isset($_POST["year"])
&& isset($_POST["course"]))
                {
                $regno=$_POST["regNo"];
                $name= $_POST["StdName"];
                $email=$_POST["email"];
                $year =$_POST["year"];
                $course=$_POST["course"];
                }
else
                {
                $error = "One or more fields are not filled";
                echo $error;
                }

if(isset($_POST["insert"]))
{
                $insertString="insert into StudentInfo values ('$regno','$name','$email','$year','$course')";
                if(!mysql_query($insertString))
                {
                die('Error : '.mysql_error());
                }
                else
                {
                echo '<br/>';
                echo '1 record added...';
                }
}

else if (isset($_POST["update"]))
{             
                $updateString = "update StudentInfo set name='$name',email='$email',year='$year',course='$course'
                where RegNo='$regno'";
               
                if(!mysql_query($updateString))
                {
                die('Error : '.mysql_error());
                }
                else
                {
                echo '<br/>';
                echo '1 record updated...';
                }
}

else if (isset($_POST["delete"]))
{
                $deleteString = "delete from StudentInfo where RegNo='$regno'";

                if(!mysql_query($deleteString))
                {
                die('Error : '.mysql_error());
                }
                else
                {
                echo '<br/>';
                echo '1 record deleted...';
                }
}

else if (isset($_POST["view"]))
{
$selectString = "select * from StudentInfo";
$comments = mysql_query($selectString);
while ($row = mysql_fetch_array($comments))
                { ?>
                <br>
                <table>
                <tr>
               
                <td><?php echo $row['RegNo']; ?> </td>
                <td><?php echo $row['name']; ?> </td>
                <td><?php echo $row['year']; ?> </td>
                </tr>
                </table>
                </br>
                <?php
                }
}

?>


                                               


Reflection

Reflection

 Main.java

package com.mtit.Labs;

import java.lang.reflect.Modifier;

public class Task1 {
      
              public static void main(String[] args) {
              try {
              Class<?> clazz = Class.forName("com.mtit.Labs.Task1");
              System.out.println(clazz.getSimpleName()); // Task1
              System.out.println(clazz.getName()); // com.mtit.Labs.Task1
              System.out.println(clazz.getPackage()); // package com.mtit.Labs
              System.out.println(clazz.getModifiers()); // 1
              System.out.println(clazz.getDeclaredMethod("main", String[].class)); // public static void com.mtit.Labs.Task1.main(java.lang.String[])

              System.out.println(Modifier.toString(clazz.getDeclaredMethod(
              "main", String[].class).getModifiers())); // public static
              } catch (ClassNotFoundException | NoSuchMethodException
              | SecurityException e) {
              e.printStackTrace();
              }
              }

Final Output

Task1
com.mtit.Labs.Task1
package com.mtit.Labs
1
public static void com.mtit.Labs.Task1.main(java.lang.String[])
public static



Task 2

Books.java

package com.mtit.lab_task_2;

public class Books {
       private String bookName = "Head First design patterns";
       public int bookCount = 20;
       public String [] authors = {"Eric Freeman", "Elisabeth Freeman"};
       public double price;
       public String getBookName() {
              return bookName;
       }
       public void setBookName(String bookName) {
              this.bookName = bookName;
       }
       public int getBookCount() {
              return bookCount;
       }
       public void setBookCount(int bookCount) {
              this.bookCount = bookCount;
       }
       public String[] getAuthors() {
              return authors;
       }
       public void setAuthors(String[] authors) {
              this.authors = authors;
       }
       public double getPrice() {
              return price;
       }
       public void setPrice(double price) {
              this.price = price;
       }
      
      

}



Main.java

package com.mtit.lab_task_2;

import java.lang.reflect.Field;
import java.util.Arrays;

public class Task2_Main {

       public static void main(String[] args) {
      

              try{
                     Books b = new Books();
                     Class<?> clazz = Class.forName("com.mtit.lab_task_2.Books");
                     Field pri_field_1 = clazz.getDeclaredField("bookName"); //use getDeclaredField since bookName is a private field

                     Field pField = clazz.getField("price"); //can use getField or getDeclaredField since price is a public field

                     Field pri_field_1 = clazz.getField("bookCount");
                     pri_field_1.setAccessible(true); //private fields have to be true to 'get' or 'set', them

                     pField.setAccessible(true);
                     pField.set(b , 2187.5);
                    
                     System.out.println(pri_field_1.getName()+" = "+pri_field_1.get(b)); //bookName = Head First design patterns

                     System.out.println("Authors = " + Arrays.asList((String [])clazz.getField("authors").get(b))); //Authors = [Eric Freeman, Elisabeth Freeman]      

      
                     System.out.println(publicField.getName()+" = "+publicField.get(b)); //bookCount = 20

                     System.out.println(pField.getName()+" = "+pField.get(b)); //price = 2187.5
                    
                    
              }catch(ClassNotFoundException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e){
                     e.printStackTrace();
              }
             


       }

}


Final Output

bookName = Head First design patterns
Authors = [Eric Freeman, Elisabeth Freeman]
bookCount = 20
price = 2187.5


Task 3

Employee.java

package com.mtit.Task_3;

public class Employee {
       private String eid = "E001";
       String ename = "Anura";
       public String address = "Colombo";
       protected double salary = 60_000.00;
       public String getEid() {
              return eid;
       }
       public void setEid(String eid) {
              this.eid = eid;
       }
       public String getEname() {
              return ename;
       }
       public void setEname(String ename) {
              this.ename = ename;
       }
       public String getAddress() {
              return address;
       }
       public void setAddress(String address) {
              this.address = address;
       }
       public double getSalary() {
              return salary;
       }
       public void setSalary(double salary) {
              this.salary = salary;
       }
      
       private String display(String eid, String ename, String address,
                     double salary) {
                     System.out.println("Method invoked successfully");
                     return eid + ", " + ename + ", " + address + ", " + salary;

// note this is a private method!

}
}


Main.java

package com.mtit.Task_3;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Task3_Main {

       public static void main(String[] args) {
              // TODO Auto-generated method stub
             
              try {
                     Class<?> clazz = Class.forName("com.mtit.Task_3.Employee");
                     Method[] methods = clazz.getDeclaredMethods(); // methods are returned as Method[] array
                    
                     for(Method method:methods)
                     {
                           System.out.println("Modifiers =>"+Modifier.toString(method.getModifiers()));
                           System.out.print("|| Return type =>"+method.getReturnType());
                           System.out.println("|| Name=> "+method.getName());
                          
                           if(method.getParameterTypes().length>0)// get the length of the parameters. if greater than 0 then there are parameters

                           {
                                  System.out.print("|| Parameters=> ");
                                  for(Class<?> t:method.getParameterTypes())//getParameterTypes() returns a Class<?>[] array.
                                  {
                                         System.out.println(t.getSimpleName()+" ");// we are accessing each element and get the simple name
                                  }
                           }
                     }
                    
             
              } catch (ClassNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
             

       }

}


Special method invocation method

package com.mtit.Task_3;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Task3_Main {

       public static void main(String[] args) {
              // TODO Auto-generated method stub
             
              try {
              Employee employee = new Employee();

              //set types of parameters to be passed for the method
              Class[] parameters = new Class[4];
              parameters[0] = String.class;
              parameters[1] = String.class;
              parameters[2] = String.class;
              parameters[3] = Double.TYPE;
             
             
             
              //get display() method of the Employee class
              Method m = employee.getClass().getDeclaredMethod("display", parameters);

              m.setAccessible(true); // display is a private method!!!!

              //invoke method with passing parameters
              String result = (String) m.invoke(employee, "e100","upul","malabe",80000.00);
              System.out.println(result);
                    
                    
                    
              } catch (NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
             

       }

}



Annotation Task

Interface Test.java

package com.mtit.Task_4;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
      
       int priority() default 1;
       String description();
       String [] groups() default "";
       String [] dependsOnMethods() default "";
      
}


TestAnnotation.java class


package com.mtit.Task_4;

public class TestAnnotation {
      
              @Test(priority = 2, dependsOnMethods = {"testCase2", "testCase3"},
                           description = "This represents annotation test case1", groups = {"com.MTIT"})
              public String testCase1(){
                     return "Annotation test case 1";
              }
             
              @Test(description = "This represents annotation test case2", groups = {"com.MTIT"})
              public String testCase2(){
                     return "Test case 2";
              }
             
              @Test(description = "This represents annotation test case3")
              public String testCase3(){
                     return "Test case 3";
              }

       }



Task4_main.java

package com.mtit.Task_4;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Task4_main {

       public static void main(String[] args) {
              // TODO Auto-generated method stub

              try{
                    
                     Method method = new TestAnnotation().getClass().getDeclaredMethod("testCase1");
                     Annotation[] annotaions = method.getDeclaredAnnotations();
                    
                     for(Annotation annotation:annotaions){
                           Test testAnnt = (Test)annotation;
                           System.out.println("Priority = " + testAnnt.priority());
                           System.out.println("Description = " + testAnnt.description());
                           System.out.println("Depends on methods = " + Arrays.toString(testAnnt.dependsOnMethods()));
                           System.out.println("Groups = " + Arrays.toString(testAnnt.groups()));
                     }
                    
              }catch(NoSuchMethodException | SecurityException e){
                     e.printStackTrace();
              }

       }

}