vineri, 3 iulie 2015

Java: Image Virtual Proxy

ImageProxyTest.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;

public class ImageProxyTest {

public static void main(String[] args) {
ImageProxyTest test = new ImageProxyTest();
try {
test.start();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}

public void start() throws MalformedURLException {
//This has a BorderLayout manager's control
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Icon icon = WebIconFactory.getIcon("http://politeia.org.ro/wp-content/uploads/2014/09/ponta-china.jpg");

ImageComponentWrapper wrapper = new ImageComponentWrapper(icon);
//ImageComponent wrapper = new ImageComponent(icon);
frame.getContentPane().add(wrapper);
frame.setSize(1000, 700);
frame.setVisible(true);
}

}


WebIconFactory.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.net.*;

public class WebIconFactory {
public static Icon getIcon(String url) throws MalformedURLException {
return new ImageProxy(new URL(url));
}

}

ImageProxy.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.net.*;

public class ImageProxy implements Icon {
ImageIcon imageIcon;
URL imageURL;
Thread retrievalThread;
boolean retriving = false;

public ImageProxy(URL url) {
imageURL = url;
}

public int getIconWidth() {
if (imageIcon != null) {
return imageIcon.getIconWidth();
} else {
return 800;
}
}
public int getIconHeight() {
if (imageIcon != null) {
return imageIcon.getIconHeight();
} else {
return 600;
}
}
public void paintIcon(final Component c, Graphics g, int x, int y) {
if (imageIcon != null) {
imageIcon.paintIcon(c, g, x, y);
} else {
g.drawString("Loading Image from web ... ", x + 300, y + 200);
if (!retriving) {
retriving = true;
retrievalThread = new Thread(new Runnable() {
public void run(){
try {
//simulate a long time to get the image
java.lang.Thread.sleep(2500);
imageIcon = new ImageIcon(imageURL, "CD Cover");
c.repaint();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
retrievalThread.start();
}

}
}

}


ImageComponentWrapper.java

package test.patterns.virtualproxy;

import java.awt.*;
import javax.swing.*;


public class ImageComponentWrapper  extends JComponent {
private Icon icon;

public ImageComponentWrapper(Icon icon) {
this.icon = icon;
}

public void setIcon(Icon icon) {
this.icon = icon;
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int x = (800 - w)/2;
int y = (600 - h)/2;
icon.paintIcon(this, g, x, y);
}

}

Icon.java

package test.patterns.virtualproxy; 

import javax.swing.*; 
import java.awt.*; 

public interface Icon { 
    public int getIconWidth(); 
    public int getIconHeight(); 
    public void paintIcon(final Component c, Graphics g, int x, int y);
}

Steps

  • >javac -d class *.java
  • >cd class
  • \class>java test.patterns.virtualproxy.ImageProxyTest


References

Head First Java, 2nd Edition By Kathy Sierra, Bert Bates

Java: Packaging and Deployment

Simple compilation and run of a Test.java file: 

  • Separate source code from class files
>javac -d class *.java
  • Running the code
>cd class
>java Test

Making an executable JAR

  • Ensure that all files are located in class directory
  • Create a manifest.txt file
    • Set the main class --> add the line below in manifest.txt:
Main-Class: ImageProxyTest

  • Run jar tool to create a jar file
>jar -cvmf manifest.txt ImageProxyTest.jar *.class
  • Run the jar 
>java -jar ImageProxyTest.jar


Others:

  • With class in a package: \class>java test.patterns.virtualproxy.ImageProxyTest
  • Check the structure of jar file: \class>jar -tf ImageProxyTest.jar


Java: Dynamic Proxy Sample

Scope: Control the access to the Employee class
Classes:

  •  interface IEmployee
  • Employee
  • EmployeeInvocationHandler
  • ReadOnlyInvocationHandler
  • Test

import java.lang.reflect.*; 
public class Test { 
    public static void main(String[] args) { 
        Test test = new Test(); 
        IEmployee employee = test.getEmployee("George", 34); 
         
        System.out.println("\tTest employeeProxy");  
        IEmployee employeeProxy = test.getEmployeeProxy(employee);
        test.testProxy(employeeProxy); 
         
        System.out.println("\tTest readOnlyProxy");  
        IEmployee readOnlyProxy = test.getReadOnlyProxy(employee);
        test.testProxy(readOnlyProxy); 
    } 
     
    IEmployee getEmployee(String name, int age) { 
        Employee employee = new Employee(); 
        employee.setName(name); 
        employee.setAge(age); 
         
        return employee; 
    } 
     
    public void testProxy(IEmployee proxy) { 
        System.out.println("Name is " + proxy.getName()); 
        System.out.println("Current age is " + proxy.getAge()); 
        try { 
            System.out.println("Set new age to 35"); 
            proxy.setAge(35); 
        } 
        catch (Exception ex) { 
            System.out.println("Cannot set the age!"); 
        } 
        try { 
            System.out.println("Set salary to 100"); 
            proxy.setSalary(100); 
        } catch (Exception ex) { 
            System.out.println("Cannot set the salary!"); 
        } 
    } 
     
    IEmployee getEmployeeProxy(IEmployee employee) { 
        return (IEmployee) Proxy.newProxyInstance( 
            employee.getClass().getClassLoader(), 
            employee.getClass().getInterfaces(), 
            new EmployeeInvocationHandler(employee)); 
    }  
     
    IEmployee getReadOnlyProxy(IEmployee employee) { 
        return (IEmployee) Proxy.newProxyInstance( 
            employee.getClass().getClassLoader(), 
            employee.getClass().getInterfaces(), 
            new ReadOnlyInvocationHandler(employee)); 
    }  
}



public interface IEmployee { 
        String getName(); 
        void setName(String name); 
         
        int getAge(); 
        void setAge(int age); 
         
        int getSalary(); 
        void setSalary(int salary); 
         
}


public class Employee implements IEmployee { 
    String name; 
    int age = 34, salary = 100; 
     
    public String getName() { 
        return name; 
    } 
    public void setName(String name) { 
        this.name = name; 
    } 
     
    public int getAge() { 
        return age; 
    } 
    public void setAge(int age) { 
        this.age = age; 
    } 
     
    public int getSalary() { 
        return salary; 
    } 
     
    public void setSalary(int salary) { 
        this.salary = salary; 
    } 
}


import java.lang.reflect.*; 
public class EmployeeInvocationHandler implements InvocationHandler {
    IEmployee employee;  
    public EmployeeInvocationHandler(IEmployee employee) { 
        this.employee = employee; 
    } 
     
    public Object invoke(Object proxy, Method method, Object[] args) 
            throws IllegalAccessException {  
         
        try { 
            //allow employee to get info about him /her 
            if (method.getName().startsWith("get")) { 
                return method.invoke(employee, args); 
            //employee is not able to set the salary 
            } else if (method.getName().equals("setSalary")) { 
                throw new IllegalAccessException(); 
            //employee is able to set other information 
            } else if (method.getName().startsWith("set")) { 
                return method.invoke(employee, args); 
            }         
        } catch(InvocationTargetException ex) { 
            ex.printStackTrace(); 
        } 
        return null
    } 
}


import java.lang.reflect.*; 
public class ReadOnlyInvocationHandler implements InvocationHandler {
    IEmployee employee;  
    public ReadOnlyInvocationHandler(IEmployee employee) { 
        this.employee = employee; 
    } 
     
    public Object invoke(Object proxy, Method method, Object[] args) 
            throws IllegalAccessException {  
        try { 
            //read only user can only get info about an employee 
            if (method.getName().startsWith("get")) { 
                return method.invoke(employee, args); 
            } else if (method.getName().startsWith("set")) { 
                throw new IllegalAccessException(); 
            }         
        } catch(InvocationTargetException ex) { 
            ex.printStackTrace(); 
        } 
        return null
    } 
}





Running the code: 

\dynamicproxy>javac -d class *.java
\dynamicproxy>cd class
\dynamicproxy\class>java Test
        Test employeeProxy
Name is George
Current age is 34
Set new age to 35
Set salary to 100
Cannot set the salary!
        Test readOnlyProxy
Name is George
Current age is 35
Set new age to 35
Cannot set the age!
Set salary to 100
Cannot set the salary!