com.app.server.node.NodeServer.java Source code

Java tutorial

Introduction

Here is the source code for com.app.server.node.NodeServer.java

Source

package com.app.server.node;

/*Copyright 2013 - 2015, Arun_Soundararajan (arun_srajan_2007@yahoo.com).and/or its affiliates.
    
All files in this repository or distribution are licensed under the
Apache License, Version 2.0 (the "License");
you may not use any files in this repository or distribution except
in compliance with the License.
    
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.Context;

import org.apache.commons.io.input.ClassLoaderObjectInputStream;
import org.apache.log4j.Logger;

import com.app.server.ServerConfig;
import com.app.server.WebClassLoader;

/**
 * This class is the implementation of the node server which gets the executor services request 
 * executed the request and sends the response back to the main server
 * @author arun
 *
 */
public class NodeServer extends Thread implements Runnable {
    static Logger log = Logger.getLogger(NodeServer.class);
    int port;
    private Vector deployerList = new Vector();
    private Vector serviceList = new Vector();
    private static RMIDeployer deployer = new RMIDeployer();

    public NodeServer(int port) {
        this.port = port;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        // TODO Auto-generated method stub
        new NodeServer(Integer.parseInt(args[0])).start();
        try {
            new NodeResourceSender(args[0], deployer);
        } catch (Exception e) {
            log.error("Error in executing the NodeSender ", e);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * This method implements the node server request
     */
    public void run() {
        //deployer.start();
        try {
            ObjectName objName = new ObjectName("com.app.server:type=deployer,service=RMIDeployer");
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            mbeanServer.createMBean("com.app.server.node.RMIDeployer", objName);
            mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                    new String[] { Vector.class.getName() });
            ServerConfig serverConfig = new ServerConfig();
            serverConfig.setRmiregistryport(port + "");
            serverConfig.setCachedir("d:/AppServer/cache");
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            InetAddress inet = null;
            inet = InetAddress.getLocalHost();
            mbeanServer.invoke(objName, "deploy",
                    new Object[] { new URL("file:///D:/AppServer/deploy/rmitest.rmi"), false, null,
                            inet.getHostName() + ":" + port },
                    new String[] { URL.class.getName(), boolean.class.getName(), ClassLoader.class.getName(),
                            String.class.getName() });
            //deployer.deploy(new URL("file:///D:/AppServer/deploy/rmitest.rmi"),false,null,inet.getHostName()+":"+port);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * This class is the implementation of the node server request processor
     * @author arun
     *
     */
    class NodeServerRequestProcessor extends Thread implements Runnable {
        Socket sock;

        public NodeServerRequestProcessor(Socket sock) {
            this.sock = sock;
        }

        public void run() {
            ObjectInputStream objinputstream = null;
            ClassLoader oldCl;
            InputStream inputStream = null;
            try {
                inputStream = sock.getInputStream();
            } catch (Exception ex) {
                log.error("Error in obtaing inputstream from socket " + sock, ex);
                // TODO Auto-generated catch block
                //e1.printStackTrace();
            }
            try {
                objinputstream = new ObjectInputStream(inputStream);
            } catch (Exception e) {
                log.error("Error in obtaing objectinputstream", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
            NodeInfo nodeInfo = null;
            CopyOnWriteArrayList<URL> classLoader = null;
            try {
                log.info("Before NodeInfo");
                nodeInfo = (NodeInfo) objinputstream.readObject();
                log.info("After NodeInfo");
            } catch (Exception e) {
                log.error("Error in obtaining the object from stream", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
            try {
                log.info("webclassloader");
                classLoader = nodeInfo.getWebclassLoaderURLS();
                log.info(nodeInfo.getClassNameWithPackage());
                WebClassLoader webClassLoader = new WebClassLoader(
                        classLoader.toArray(new URL[classLoader.size()]));
                //oldCl=Thread.currentThread().getContextClassLoader();
                //Thread.currentThread().setContextClassLoader(webClassLoader);
                NodeInfoMethodParam nodeInfoMethodParam = null;
                try {
                    objinputstream = new NodeObjectInputStream(webClassLoader, inputStream);
                    nodeInfoMethodParam = (NodeInfoMethodParam) objinputstream.readObject();
                } catch (Exception e) {
                    log.error("Error in obtaining the object from stream", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }

                Class cls = webClassLoader.loadClass(nodeInfo.getClassNameWithPackage());
                Object obj = cls.newInstance();
                //               System.out.println(nodeInfo.getMethodParamTypes());
                //               System.out.println("InetAddress="+nodeInfo.getSock().getInputStream());;
                //               System.out.println("InetAddress1="+nodeInfo.getSock().getLocalPort());;
                //               System.out.println("InetAddress2="+nodeInfo.getSock().getPort());;
                //System.out.println("InetAddress3="+nodeInfo.getOstream());;
                //nodeInfo.getOstream().close();
                //System.out.println("InetAddress="+nodeInfo.getSock().bind(new InetSocketAddress("192.168.0.1", 0)));;
                log.info(nodeInfoMethodParam.getMethodParamTypes()[0]);
                Method method = cls.getMethod(nodeInfo.getMethodName(), nodeInfoMethodParam.getMethodParamTypes());
                Object returnValue = method.invoke(obj, nodeInfoMethodParam.getMethodParams());
                ObjectOutputStream objoutputstream = null;
                //Thread.currentThread().setContextClassLoader(oldCl);
                try {
                    objoutputstream = new ObjectOutputStream(sock.getOutputStream());
                    objoutputstream.writeObject(returnValue);
                } catch (Exception e) {
                    log.error("Error in writing the object to stream", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
                log.info(obj);
                objinputstream.close();
                objoutputstream.close();
            } catch (Exception e) {
                log.error("Error in processing the executor ", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            } finally {
                try {
                    sock.close();
                } catch (Exception e) {
                    log.error("Error in closing the socket ", e);
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }
            }
        }

    }
}