Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Friday, October 4, 2013

Java: Reflecting to Get All Classes in a Package, check and invoke method dynamically

It took me a little while to figure out that Java doesn't provide a way to reflect an entire package. In other words, there is no built-in way for me to dynamically retrieve a list of all the classes in a given package in Java through reflection. So I wrote my own method to do it.
Since it took a bit of googling and effort, I thought it would be nice to share the convenience method I wrote with the world. Enjoy:

Main.java under code.com.pritom package

package code.com.pritom;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

public class Main {
    java.lang.reflect.Method method;

    public static void main(String[] args) throws Exception{
        Main main = new Main();
    }

    public Main() throws Exception{
        Class loadClass = getClassObjectByName("Load");
        System.out.println("Product Type Class: " + loadClass);
        System.out.println("Product Type Simple Name: " + loadClass.getSimpleName());
        System.out.println("Product Type Package Name: " + loadClass.getPackage().getName());
        System.out.println("Product Type Is Enum: " + loadClass.isEnum());

        try {
            method = loadClass.getMethod("println", String.class);
            System.out.println("Method Exists: println(String.class)");
            method.invoke(loadClass.newInstance(), "Pritom");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        try {
            Class[] classes = new Class[2];
            classes[0] = String.class;
            classes[1] = Integer.class;
            method = loadClass.getMethod("println", classes);
            System.out.println("Method Exists: println(String.class, Integer.class)");
            method.invoke(loadClass.newInstance(), "Pritom", 26);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    private static HashMap allClassList = new HashMap();
    private static HashMap classObjectList = new HashMap();
    private static HashMap allClassObjectList = new HashMap();

    public static Class getClassObjectByName(String name) throws Exception {
        if(allClassObjectList.containsKey(name)) {
            return (Class) allClassObjectList.get(name);
        }
        String packageName = "code.com.pritom";
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<String> classes = new ArrayList<String>();
        for (File directory : dirs) {
            findClasses(directory, packageName);
        }
        if(allClassList.containsKey(name)) {
            Object object = getClassObjectByFullName(allClassList.get(name).toString()); /* Get the object */
            allClassObjectList.put(name, object); /* Storing for further use by class name only */
            return (Class) object; /* Return object */
        }
        throw new Exception("Invalid entity '" + name + "'");
    }

    private static void findClasses(File directory, String packageName) throws ClassNotFoundException {
        if (!directory.exists()) {
            return;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                findClasses(file, packageName + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                allClassList.put(file.getName().substring(0, file.getName().length() - 6), packageName + "." + file.getName().substring(0, file.getName().length() - 6));
            }
        }
    }

    private static Object getClassObjectByFullName(String fullName) throws Exception {
        if (classObjectList.containsKey(fullName)) {
            return classObjectList.get(fullName);
        }
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Object object = Class.forName(fullName, true, classLoader);
            classObjectList.put(fullName, object); /* Storing by (package + class) name */
            return object;
        } catch (Exception ex) {
            throw new Exception(fullName + " does not appear to be a valid class.");
        }
    }
}

And Load.java under code.com.pritom package


package code.com.pritom;

public class Load {
    public void println(String text) {
        System.out.println("\tName: " + text);
    }
    public void println(String text, Integer age) {
        System.out.println("\tName: " + text +", Age: " + age);
    }
}


And output will be as follows:


Product Type Class: class code.com.pritom.Load
Product Type Simple Name: Load
Product Type Package Name: code.com.pritom
Product Type Is Enum: false
Method Exists: println(String.class)
	Name: Pritom
Method Exists: println(String.class, Integer.class)
	Name: Pritom, Age: 26

Monday, September 30, 2013

[Java/Grails] Class ConstrainedProperty

org.codehaus.groovy.grails.validation

[Java/Grails] Class ConstrainedProperty

java.lang.Object
  org.codehaus.groovy.grails.validation.ConstrainedProperty 
 


Method Summary
void addMetaConstraint(java.lang.String name, java.lang.Object value)
Obtains the value of the named meta constraint.
void applyConstraint(java.lang.String constraintName, java.lang.Object constrainingValue)
Applies a constraint for the specified name and consraint value.
Constraint getAppliedConstraint(java.lang.String name)
@param constraintName The name of the constraint to check
java.util.Collection getAppliedConstraints()
Obtains an applied constraint by name.
java.util.Map getAttributes()
java.lang.String getFormat()
java.util.List getInList()
@return Returns the inList.
java.lang.String getMatches()
@return Returns the matches.
java.lang.Comparable getMax()
java.lang.Integer getMaxSize()
java.lang.Object getMetaConstraintValue(java.lang.String name)
java.lang.Comparable getMin()
@return Returns the min.
java.lang.Integer getMinSize()
@return Returns the minSize.
java.lang.Object getNotEqual()
@return Returns the notEqual.
int getOrder()
@param order The order to set.
java.lang.String getPropertyName()
@return Returns the propertyName.
java.lang.Class getPropertyType()
@return Returns the max.
groovy.lang.Range getRange()
@return Returns the range.
java.lang.Integer getScale()
@return The scale, if defined for this property; null, otherwise
groovy.lang.Range getSize()
@param size The size to set.
java.lang.String getWidget()
boolean hasAppliedConstraint(java.lang.String constraintName)
@return Returns the propertyType.
static boolean hasRegisteredConstraint(java.lang.String constraintName)
@return Returns the appliedConstraints.
boolean isBlank()
@return the blank.
boolean isCreditCard()
boolean isDisplay()
@return Returns the display.
boolean isEditable()
@param editable The editable to set.
boolean isEmail()
@return Returns the email.
boolean isNullable()
@return Returns the nullable.
boolean isPassword()
boolean isUrl()
static void registerNewConstraint(java.lang.String name, java.lang.Class constraintClass)
static void registerNewConstraint(java.lang.String name, ConstraintFactory factory)
static void removeConstraint(java.lang.String name, java.lang.Class constraintClass)
static void removeConstraint(java.lang.String name)
void setAttributes(java.util.Map attributes)
void setBlank(boolean blank)
void setCreditCard(boolean creditCard)
void setDisplay(boolean display)
@return Returns the editable.
void setEditable(boolean editable)
@return Returns the order.
void setEmail(boolean email)
void setFormat(java.lang.String format)
void setInList(java.util.List inList)
void setMatches(java.lang.String regex)
void setMax(java.lang.Comparable max)
@param max The max to set.
void setMaxSize(java.lang.Integer maxSize)
@param maxSize The maxSize to set.
void setMessageSource(org.springframework.context.MessageSource source)
void setMin(java.lang.Comparable min)
@param min The min to set.
void setMinSize(java.lang.Integer minSize)
@param minSize The minLength to set.
void setNotEqual(java.lang.Object notEqual)
@param notEqual The notEqual to set.
void setNullable(boolean nullable)
void setOrder(int order)
void setPassword(boolean password)
void setPropertyName(java.lang.String propertyName)
@return Returns the url.
void setRange(groovy.lang.Range range)
void setSize(groovy.lang.Range size)
void setUrl(boolean url)
void setWidget(java.lang.String widget)
boolean supportsContraint(java.lang.String constraintName)
Checks with this ConstraintedProperty instance supports applying the specified constraint.
java.lang.String toString()
void validate(java.lang.Object target, java.lang.Object propertyValue, org.springframework.validation.Errors errors)

Tuesday, February 26, 2013

simple class for calling a url using either curl or fopen


<?php
class EmailManager {
    var $_server;
    var $_account;

    const client_login_url = 'https://www.google.com/accounts/ClientLogin';

    function __construct($params = array())
    {
        if(!isset($params["server"])) {
            throw new Exception("Server name required.");
        }
        if(!isset($params["account"])) {
            throw new Exception("Account name required.");
        }
        $this->_account = $params["account"];
        $this->_server = $params["server"];
    }

    protected function authenticateUser($email, $password)
    {
        $postVariables = array(
            'accountType' => 'GOOGLE',
            'Email' => $email,
            'Passwd' => $password,
            'service' => 'analytics'
        );
        $response = $this->httpRequest(EmailManager::client_login_url, null, $postVariables);
    }

    protected function httpRequest($url, $get_variables=null, $post_variables=null, $headers=null)
    {
        $interface = null;
        if(function_exists('curl_exec')) {
            $interface = 'curl';
        } else {
            $interface = 'fopen';
        }
        if($interface == 'curl') {
            return $this->curlRequest($url, $get_variables, $post_variables, $headers);
        } else if($interface == 'fopen') {
            return $this->fOpenRequest($url, $get_variables, $post_variables, $headers);
        }
    }

    private function curlRequest($url, $get_variables=null, $post_variables=null, $headers=null)
    {
        $ch = curl_init();

        if(is_array($get_variables))
        {
            $get_variables = '?' . str_replace('&amp;','&',urldecode(http_build_query($get_variables)));
        }
        else
        {
            $get_variables = null;
        }

        curl_setopt($ch, CURLOPT_URL, $url . $get_variables);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //CURL doesn't like google's cert

        if(is_array($post_variables))
        {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_variables);
        }

        if(is_array($headers))
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        }

        $response = curl_exec($ch);
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

        curl_close($ch);

        return array('body'=>$response,'code'=>$code);
    }

    private function fOpenRequest($url, $get_variables=null, $post_variables=null, $headers=null)
    {
        $http_options = array('method'=>'GET','timeout'=>3);

        if(is_array($headers))
        {
            $headers = implode("\r\n",$headers) . "\r\n";
        }
        else
        {
            $headers = '';
        }

        if(is_array($get_variables))
        {
            $get_variables = '?' . str_replace('&amp;','&',urldecode(http_build_query($get_variables)));
        }
        else
        {
            $get_variables = null;
        }

        if(is_array($post_variables))
        {
            $post_variables = str_replace('&amp;','&',urldecode(http_build_query($post_variables)));
            $http_options['method'] = 'POST';
            $headers = "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($post_variables) . "\r\n" . $headers;
            $http_options['header'] = $headers;
            $http_options['content'] = $post_variables;
        }
        else
        {
            $post_variables = '';
            $http_options['header'] = $headers;
        }

        $context = stream_context_create(array('http'=>$http_options));
        $response = @file_get_contents($url . $get_variables, null, $context);

        return array('body'=>$response!==false?$response:'Request failed, fopen provides no further information','code'=>$response!==false?'200':'400');
    }
}
?>