List of usage examples for java.rmi.server UnicastRemoteObject exportObject
private static Remote exportObject(Remote obj, UnicastServerRef sref) throws RemoteException
From source file:com.vmware.identity.idm.server.IdmServer.java
/** * Initialize the IDM service./* w w w . j a v a 2 s . c o m*/ * * @throws Exception when something goes wrong with initialization. */ private static void initialize() throws Exception { try (IDiagnosticsContextScope diagCtxt = DiagnosticsContextFactory.createContext("IDM Startup", "")) { logger.info("Starting IDM Server..."); logger.debug("Creating RMI registry on port {}", Tenant.RMI_PORT); boolean allowRemoteConnections = Boolean .parseBoolean(System.getProperty(ALLOW_REMOTE_PROPERTY, "false")); if (allowRemoteConnections) { logger.warn("RMI registry is allowing remote connections!"); registry = LocateRegistry.createRegistry(Tenant.RMI_PORT); } else { logger.debug("RMI registry is restricted to the localhost"); RMIClientSocketFactory csf = RMISocketFactory.getDefaultSocketFactory(); RMIServerSocketFactory ssf = new LocalRMIServerSocketFactory(); registry = LocateRegistry.createRegistry(Tenant.RMI_PORT, csf, ssf); } // Assign a security manager, in the event that dynamic classes are loaded if (System.getSecurityManager() == null) { logger.debug("Creating RMI Security Manager..."); System.setSecurityManager(new RMISecurityManager()); } logger.debug("Creating Config Store factory..."); IConfigStoreFactory cfgStoreFactory = new ConfigStoreFactory(); logger.debug("Creating Identity Provider factory..."); IProviderFactory providerFactory = new ProviderFactory(); logger.debug("Checking VMware Directory Service..."); ServerUtils.check_directory_service(); logger.debug("Setting system properties..."); System.setProperties(new ThreadLocalProperties(System.getProperties())); logger.debug("Creating Identity Manager instance..."); manager = new IdentityManager(cfgStoreFactory, providerFactory); String rmiAddress = String.format("rmi://localhost:%d/%s", Tenant.RMI_PORT, IDENTITY_MANAGER_BIND_NAME); logger.debug("Binding to RMI address '{}'", rmiAddress); loginManager = new IdmLoginManager(manager); ILoginManager stub = (ILoginManager) UnicastRemoteObject.exportObject(loginManager, 0); Naming.rebind(rmiAddress, stub); startHeartbeat(); logger.info(VmEvent.SERVER_STARTED, "IDM Server has started"); } catch (Throwable t) { logger.error(VmEvent.SERVER_FAILED_TOSTART, "IDM Server has failed to start", t); throw t; } }
From source file:com.app.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory./* ww w.j av a 2 s .c om*/ */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); log.info(customClassLoader.geturlS()); customClassLoader.addURL(new URL("file:/" + files[i].getAbsolutePath())); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) customClassLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/"))); log.info("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); log.info("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //log.info("executor class in ExecutorServicesConstruct"+executorServiceClass); //log.info(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); log.info(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //log.info("method="+executorServiceAnnot.servicename()); //log.info("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:com.web.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory.//from w w w . ja va2s .com */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); System.out.println(customClassLoader.geturlS()); new WebServer().addURL(new URL("file:/" + files[i].getAbsolutePath()), customClassLoader); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) new WebServer().addURL(new URL("file:/" + jarFilePath.replace("\\", "/")), customClassLoader); System.out.println("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); System.out.println(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //System.out.println("method="+executorServiceAnnot.servicename()); //System.out.println("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:com.app.server.EJBDeployer.java
public void deployEjbJar(URL url, StandardFileSystemManager manager, ClassLoader cL) { try {/* w w w.j ava2 s.c o m*/ Vector<EJBContext> ejbContexts = null; EJBContext ejbContext; log.info(url.toURI()); ConcurrentHashMap<String, RARArchiveData> rardata = (ConcurrentHashMap<String, RARArchiveData>) mbeanServer .getAttribute(rarDeployerName, "RARArchiveDataAllAdapters"); Collection<RARArchiveData> rarcls = rardata.values(); Iterator<RARArchiveData> rarcl = rarcls.iterator(); RARArchiveData rararcdata; FileObject filetoScan = manager.resolveFile("jar:" + url.toString() + "!/"); HashSet<Class<?>>[] classes = new HashSet[] { new HashSet(), new HashSet(), new HashSet() }; VFSClassLoader jarCL; if (cL != null) { jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, cL); } else { jarCL = new VFSClassLoader(new FileObject[] { filetoScan }, manager, Thread.currentThread().getContextClassLoader()); } Class[] annot = new Class[] { Stateless.class, Stateful.class, MessageDriven.class }; scanJar(filetoScan, classes, annot, jarCL); Set<Class<?>> clsStateless = classes[0]; Set<Class<?>> clsStateful = classes[1]; Set<Class<?>> clsMessageDriven = classes[2]; //System.gc(); staticObjs = null; EJBContainer container = EJBContainer.getInstance(classes); container.inject(); if (clsStateless.size() > 0) { staticObjs = new Vector<Object>(); ejbContexts = new Vector<EJBContext>(); ejbContext = new EJBContext(); ejbContext.setJarPath(url.toString()); ejbContext.setJarDeployed(url.toString()); for (Class<?> ejbInterface : clsStateless) { BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); proxyobj = factory.createWithBean(obj); staticObjs.add(proxyobj); Object unicastobj = UnicastRemoteObject.exportObject((Remote) proxyobj, 0); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { // registry.unbind(remoteBinding); ic.bind("java:/" + remoteBinding, (Remote) unicastobj); ejbContext.put(remoteBinding, obj.getClass()); //registry.rebind(remoteBinding, (Remote)unicastobj); } // registry.rebind("name", (Remote) obj); } ejbContexts.add(ejbContext); jarEJBMap.put(url.toString(), ejbContexts); } if (clsStateful.size() > 0) { if (staticObjs == null) { staticObjs = new Vector<Object>(); } if (ejbContexts == null) { ejbContexts = new Vector<EJBContext>(); } ejbContext = new EJBContext(); ejbContext.setJarPath(url.toString()); ejbContext.setJarDeployed(url.toString()); StatefulBeanObject statefulBeanObject = null; for (Class<?> ejbInterface : clsStateful) { BeanPool.getInstance().create(ejbInterface); obj1 = ejbInterface.newInstance(); if (statefulBeanObject == null) { statefulBeanObject = new StatefulBeanObject(obj1, url.toString()); } else { statefulBeanObject.addStatefulSessionBeanObject(obj1); } //System.out.println(obj1); staticObjs.add(statefulBeanObject); /*Object unicastobj1 = UnicastRemoteObject.exportObject( (Remote) obj1, 0);*/ String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + statefulBeanObject); if (remoteBinding != null) { // registry.unbind(remoteBinding); ic.bind("java:/" + remoteBinding, statefulBeanObject); ejbContext.put(remoteBinding, statefulBeanObject.getClass()); //registry.rebind(remoteBinding, (Remote)unicastobj1); } // registry.rebind("name", (Remote) obj); } ejbContexts.add(ejbContext); jarEJBMap.put(url.toString(), ejbContexts); } if (clsMessageDriven.size() > 0) { MDBContext mdbContext = null; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(url.toString()) != null) { mdbContexts = jarMDBMap.get(url.toString()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(url.toString(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); //System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); //System.out.println("classList:" // + classwithpackage.replace("/", ".")); final Class mdbBeanCls = mdbBean; try { if (!classwithpackage.contains("$")) { // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); // System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { Adapter adapter = null; ActivationConfigProperty[] activationConfigProp = null; for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof Adapter) { adapter = (Adapter) classServicesAnnot[annotcount]; } else if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; activationConfigProp = messageDrivenAnnot.activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); } } if (adapter != null) { /*if(rarcl.hasNext()){ rararcdata=rardata.get(rarDeployerName); rararcdata=rarcl.next(); //classLoader = new VFSClassLoader(rararcdata.getVfsClassLoader().getFileObjects(),rararcdata.getFsManager(),classLoader); FileObject[] fileObjectArray=rararcdata.getVfsClassLoader().getFileObjects(); //urlset.addAll(ClasspathHelper.forClassLoader(rararcdata.getVfsClassLoader())); for(FileObject fileObject:fileObjectArray){ fileObjects.add(fileObject.getURL()); //urlset.add(fileObject.getURL()); //System.out.println(Vfs.fromURL(fileObject.getURL()).getFiles().iterator().next().getRelativePath()); } classLoader = new URLClassLoader(fileObjects.toArray(new URL[fileObjects.size()]),Thread.currentThread().getContextClassLoader()); }*/ RARArchiveData rarArchiveData = (RARArchiveData) mbeanServer.invoke( rarDeployerName, "getRARArchiveData", new Object[] { adapter.adapterName() }, new String[] { String.class.getName() }); if (rarArchiveData == null) throw new Exception("RAR Adapter " + adapter.adapterName() + " Not found in deploy folder"); Class resourceAdapterClass = rarArchiveData.getResourceAdapterClass(); final ResourceAdapter resourceAdapter = (ResourceAdapter) resourceAdapterClass .newInstance(); Class activationSpecClass = rarArchiveData.getActivationspecclass(); final ActivationSpec activationSpec = (ActivationSpec) activationSpecClass .newInstance(); Vector<ConfigProperty> configProperties = rarArchiveData.getConfigPropery(); Integer configPropertyInteger; Long configPropertyLong; Boolean configPropertyBoolean; Method method; if (configProperties != null) { for (ConfigProperty configProperty : configProperties) { String property = configProperty.getConfigpropertyname(); property = (property.charAt(0) + "").toUpperCase() + property.substring(1); Class propertytype = Class .forName(configProperty.getConfigpropertytype()); try { method = activationSpecClass.getMethod("set" + property, propertytype); if (propertytype == String.class) { method.invoke(activationSpec, configProperty.getConfigpropertyvalue()); ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } else if (propertytype == Integer.class) { if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { configPropertyInteger = new Integer( configProperty.getConfigpropertyvalue()); try { method.invoke(activationSpec, configPropertyInteger); } catch (Exception ex) { method.invoke(activationSpec, configPropertyInteger.intValue()); } ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } } else if (propertytype == Long.class) { if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { configPropertyLong = new Long( configProperty.getConfigpropertyvalue()); method.invoke(activationSpec, configPropertyLong); ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } } else if (propertytype == Boolean.class) { if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { configPropertyBoolean = new Boolean( configProperty.getConfigpropertyvalue()); method.invoke(activationSpec, configPropertyBoolean); ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } } } catch (Exception ex) { try { if (propertytype == Integer.class) { method = activationSpecClass.getMethod("set" + property, int.class); if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { method = activationSpecClass .getMethod("set" + property, int.class); configPropertyInteger = new Integer( configProperty.getConfigpropertyvalue()); method.invoke(activationSpec, configPropertyInteger.intValue()); //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty); } } else if (propertytype == Long.class) { if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { method = activationSpecClass .getMethod("set" + property, long.class); configPropertyLong = new Long( configProperty.getConfigpropertyvalue()); method.invoke(activationSpec, configPropertyLong.longValue()); //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty); } } else if (propertytype == Boolean.class) { if (configProperty.getConfigpropertyvalue() != null && !configProperty.getConfigpropertyvalue() .equalsIgnoreCase("")) { method = activationSpecClass .getMethod("set" + property, boolean.class); configPropertyBoolean = new Boolean( configProperty.getConfigpropertyvalue()); method.invoke(activationSpec, configPropertyBoolean.booleanValue()); //ConfigResourceAdapter(resourceAdapterClass,propertytype,resourceAdapter,property,configProperty); } } ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } catch (Exception ex1) { ConfigResourceAdapter(resourceAdapterClass, propertytype, resourceAdapter, property, configProperty); } //log.error("Could not set Configuration for rar activation spec", ex); } } } for (ActivationConfigProperty activationConfig : activationConfigProp) { String property = activationConfig.propertyName(); property = (property.charAt(0) + "").toUpperCase() + property.substring(1); try { method = activationSpecClass.getMethod("set" + property, String.class); method.invoke(activationSpec, activationConfig.propertyValue()); } catch (Exception ex) { try { method = activationSpecClass.getMethod("set" + property, boolean.class); method.invoke(activationSpec, new Boolean(activationConfig.propertyValue())); } catch (Exception ex1) { method = activationSpecClass.getMethod("set" + property, Boolean.class); method.invoke(activationSpec, new Boolean(activationConfig.propertyValue())); } } } final Class listenerClass = rarArchiveData.getMessagelistenertype(); ClassLoader cCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread() .setContextClassLoader(resourceAdapter.getClass().getClassLoader()); resourceAdapter .start(new com.app.server.connector.impl.BootstrapContextImpl()); MessageEndPointFactoryImpl messageEndPointFactoryImpl = new MessageEndPointFactoryImpl( listenerClass, mdbBeanCls.newInstance(), jarCL); resourceAdapter.endpointActivation(messageEndPointFactoryImpl, activationSpec); Thread.currentThread().setContextClassLoader(cCL); if (mdbContext != null) { mdbContext.setResourceAdapter(resourceAdapter); mdbContext.setMessageEndPointFactory(messageEndPointFactoryImpl); mdbContext.setActivationSpec(activationSpec); mdbContexts.put(mdbContext.getMdbName(), mdbContext); } /*new Thread(){ public void run(){ try { resourceAdapter.endpointActivation(new com.app.server.connector.impl.MessageEndPointFactoryImpl(listenerClass, mdbBeanCls.newInstance(),raCl), activationSpec); } catch ( Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start();*/ } else { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } } catch (Exception e) { log.error("Error : ", e); // TODO Auto-generated catch block //e.printStackTrace(); } } } if (staticObjs != null) { staticObjsEjbMap.put(url.toString(), staticObjs); } this.jarsDeployed.add(url.toURI().toString()); log.info(url.toString() + " Deployed"); } catch (Exception ex) { log.error("Error in deploying the jar file: " + url, ex); //ex.printStackTrace(); } finally { /*if(classLoader!=null){ try { classLoader.close(); } catch (Exception e) { log.error("error in closing the classloader", e); // TODO Auto-generated catch block //e.printStackTrace(); } ClassLoaderUtil.closeClassLoader(classLoader); }*/ } }
From source file:com.healthmarketscience.rmiio.RemoteStreamServerTest.java
@SuppressWarnings("unchecked") public static List<List<File>> mainTest(String[] args, final List<Throwable> clientExceptions, final List<AccumulateRemoteStreamMonitor<?>> monitors) throws Exception { final String testFile = args[0]; final boolean doAbort = ((args.length > 1) ? Boolean.parseBoolean(args[1]) : false); final boolean reverse = ((args.length > 2) ? Boolean.parseBoolean(args[2]) : false); final boolean doSkip = ((args.length > 3) ? Boolean.parseBoolean(args[3]) : false); final boolean doFastTests = ((args.length > 4) ? Boolean.parseBoolean(args[4]) : false); final List<List<File>> tempFiles = Arrays.asList(Collections.synchronizedList(new LinkedList<File>()), Collections.synchronizedList(new LinkedList<File>())); FileServer server = new FileServer(testFile, tempFiles, monitors); final RemoteFileServer stub = (RemoteFileServer) simulateRemote( UnicastRemoteObject.exportObject(server, 0)); LOG.debug("Server ready"); LOG.debug("Sleeping 3000 ms..."); Thread.sleep(3000);//from ww w.j av a 2 s. c om LOG.debug("Running 'reliable' tests"); Thread clientThread = new Thread(new Runnable() { public void run() { clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip, false, doFastTests, monitors)); } }); clientThread.start(); clientThread.join(); if (!doFastTests) { server.setUnreliable(true); LOG.debug("Running 'unreliable' tests"); clientThread = new Thread(new Runnable() { public void run() { clientExceptions.addAll(FileClient.main(stub, testFile, tempFiles, doAbort, reverse, doSkip, true, doFastTests, monitors)); } }); clientThread.start(); clientThread.join(); } LOG.debug("Unexporting server"); UnicastRemoteObject.unexportObject(server, true); return tempFiles; }
From source file:com.web.server.EARDeployer.java
/** * This method configures the executor services from the jar file. * // w w w . j a v a 2s . co m * @param jarFile * @param classList * @throws FileSystemException */ public void deployExecutorServicesEar(String earFileName, FileObject earFile, StandardFileSystemManager fsManager) throws FileSystemException { try { System.out.println("EARFILE NAMEs=" + earFileName); CopyOnWriteArrayList<FileObject> fileObjects = new CopyOnWriteArrayList<FileObject>(); CopyOnWriteArrayList<FileObject> warObjects = new CopyOnWriteArrayList<FileObject>(); ConcurrentHashMap jarClassListMap = new ConcurrentHashMap(); CopyOnWriteArrayList<String> classList; obtainUrls(earFile, earFile, fileObjects, jarClassListMap, warObjects, fsManager); VFSClassLoader customClassLoaderBaseLib = new VFSClassLoader( fileObjects.toArray(new FileObject[fileObjects.size()]), fsManager, Thread.currentThread().getContextClassLoader()); VFSClassLoader customClassLoader = null; Set keys = jarClassListMap.keySet(); Iterator key = keys.iterator(); FileObject jarFileObject; ConcurrentHashMap classLoaderPath = new ConcurrentHashMap(); filesMap.put(earFileName, classLoaderPath); for (FileObject warFileObj : warObjects) { if (warFileObj.getName().getBaseName().endsWith(".war")) { //logger.info("filePath"+filePath); String filePath = scanDirectory + "/" + warFileObj.getName().getBaseName(); log.info(filePath); String fileName = warFileObj.getName().getBaseName(); WebClassLoader classLoader = new WebClassLoader(new URL[] {}); log.info(classLoader); warDeployer.deleteDir( new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")))); new File(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))).mkdirs(); log.info(deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))); urlClassLoaderMap.put( deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war")), classLoader); classLoaderPath.put(warFileObj.getName().getBaseName(), deployDirectory + "/" + fileName.substring(0, fileName.lastIndexOf(".war"))); warDeployer.extractWar(new File(filePath), classLoader); if (exec != null) { exec.shutdown(); } new File(scanDirectory + "/" + warFileObj.getName().getBaseName()).delete(); exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS); } } for (int keyCount = 0; keyCount < keys.size(); keyCount++) { jarFileObject = (FileObject) key.next(); { classList = (CopyOnWriteArrayList<String>) jarClassListMap.get(jarFileObject); customClassLoader = new VFSClassLoader(jarFileObject, fsManager, customClassLoaderBaseLib); this.urlClassLoaderMap.put( scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName(), customClassLoader); classLoaderPath.put(jarFileObject.getName().getBaseName(), scanDirectory + "/" + earFileName + "/" + jarFileObject.getName().getBaseName()); for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); // System.out.println("classList:"+classwithpackage.replace("/",".")); try { if (!classwithpackage.contains("$")) { /*System.out.println("EARFILE NAME="+fileName); System.out .println(scanDirectory + "/" + fileName + "/" + jarFileObject.getName() .getBaseName()); System.out.println(urlClassLoaderMap);*/ Class executorServiceClass = customClassLoader.loadClass(classwithpackage); Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); System.out.println(remoteCall.servicename().trim()); try { for (int count = 0; count < 2; count++) { RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject( (Remote) executorServiceClass.newInstance(), 0); registry.rebind(remoteCall.servicename().trim(), reminterface); } } catch (Exception ex) { ex.printStackTrace(); } } } } // System.out.println(executorServiceClass.newInstance()); // System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); // System.out.println(); Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); // System.out.println("serice name=" // + executorServiceAnnot // .servicename()); // System.out.println("method info=" // + executorServiceInfo); // System.out.println(method); // if(servicesMap.get(executorServiceAnnot.servicename())==null)throw // new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } jarFileObject.close(); } for (FileObject fobject : fileObjects) { fobject.close(); } System.out.println("Channel unlocked"); earFile.close(); fsManager.closeFileSystem(earFile.getFileSystem()); // ClassLoaderUtil.closeClassLoader(customClassLoader); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.web.server.EJBDeployer.java
@Override public void fileChanged(FileChangeEvent arg0) throws Exception { try {/*from w w w . j a va 2s. c om*/ FileObject baseFile = arg0.getFile(); EJBContext ejbContext; if (baseFile.getName().getURI().endsWith(".jar")) { fileDeleted(arg0); URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config); container.inject(); Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (cls.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(baseFile.getName().getURI()); ejbContext.setJarDeployed(baseFile.getName().getBaseName()); for (Class<?> ejbInterface : cls) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put(baseFile.getName().getURI(), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(baseFile.getName().getURI()) != null) { mdbContexts = jarMDBMap.get(baseFile.getName().getURI()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(baseFile.getName().getURI(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); System.out.println(baseFile.getName().getURI() + " Deployed"); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:de.clusteval.framework.ClustevalBackendServer.java
/** * A helper method for {@link #ClusteringEvalFramework(Repository)}, which * registers the new backend server instance in the RMI registry. * //from w w w.j a v a2s. c o m * @param framework * The backend server to register. * @return True, if the server has been registered successfully */ protected static boolean registerServer(ClustevalBackendServer framework) { Logger log = LoggerFactory.getLogger(ClustevalBackendServer.class); try { LocateRegistry.createRegistry(port); IBackendServer stub = (IBackendServer) UnicastRemoteObject.exportObject(framework, port); Registry registry = LocateRegistry.getRegistry(port); registry.bind("EvalServer", stub); log.info("Framework up and listening on port " + port); log.info("Used number of processors: " + config.numberOfThreads); return true; } catch (AlreadyBoundException e) { log.error("Another instance is already running..."); return false; } catch (RemoteException e) { log.error("Another instance is already running..."); return false; } }
From source file:com.web.server.EJBDeployer.java
@Override public void fileCreated(FileChangeEvent arg0) throws Exception { try {/* ww w .j av a 2 s.c om*/ FileObject baseFile = arg0.getFile(); EJBContext ejbContext; if (baseFile.getName().getURI().endsWith(".jar")) { System.out.println(baseFile.getName().getURI()); URLClassLoader classLoader = new URLClassLoader(new URL[] { new URL(baseFile.getName().getURI()) }, Thread.currentThread().getContextClassLoader()); ConfigurationBuilder config = new ConfigurationBuilder(); config.addUrls(ClasspathHelper.forClassLoader(classLoader)); config.addClassLoader(classLoader); org.reflections.Reflections reflections = new org.reflections.Reflections(config); EJBContainer container = EJBContainer.getInstance(baseFile.getName().getURI(), config); container.inject(); Set<Class<?>> clsStateless = reflections.getTypesAnnotatedWith(Stateless.class); Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class); Object obj; System.gc(); if (clsStateless.size() > 0) { ejbContext = new EJBContext(); ejbContext.setJarPath(baseFile.getName().getURI()); ejbContext.setJarDeployed(baseFile.getName().getBaseName()); for (Class<?> ejbInterface : clsStateless) { //BeanPool.getInstance().create(ejbInterface); obj = BeanPool.getInstance().get(ejbInterface); System.out.println(obj); ProxyFactory factory = new ProxyFactory(); obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj), servicesRegistryPort); String remoteBinding = container.getRemoteBinding(ejbInterface); System.out.println(remoteBinding + " for EJB" + obj); if (remoteBinding != null) { //registry.unbind(remoteBinding); registry.rebind(remoteBinding, (Remote) obj); ejbContext.put(remoteBinding, obj.getClass()); } //registry.rebind("name", (Remote) obj); } jarEJBMap.put(baseFile.getName().getURI(), ejbContext); } System.out.println("Class Message Driven" + clsMessageDriven); System.out.println("Class Message Driven" + clsMessageDriven); if (clsMessageDriven.size() > 0) { System.out.println("Class Message Driven"); MDBContext mdbContext; ConcurrentHashMap<String, MDBContext> mdbContexts; if (jarMDBMap.get(baseFile.getName().getURI()) != null) { mdbContexts = jarMDBMap.get(baseFile.getName().getURI()); } else { mdbContexts = new ConcurrentHashMap<String, MDBContext>(); } jarMDBMap.put(baseFile.getName().getURI(), mdbContexts); MDBContext mdbContextOld; for (Class<?> mdbBean : clsMessageDriven) { String classwithpackage = mdbBean.getName(); System.out.println("class package" + classwithpackage); classwithpackage = classwithpackage.replace("/", "."); System.out.println("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass); //System.out.println(); if (!mdbBean.isInterface()) { Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof MessageDriven) { MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount]; ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot .activationConfig(); mdbContext = new MDBContext(); mdbContext.setMdbName(messageDrivenAnnot.name()); for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) { if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATIONTYPE)) { mdbContext.setDestinationType( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.DESTINATION)) { mdbContext.setDestination( activationConfigProperty.propertyValue()); } else if (activationConfigProperty.propertyName() .equals(MDBContext.ACKNOWLEDGEMODE)) { mdbContext.setAcknowledgeMode( activationConfigProperty.propertyValue()); } } if (mdbContext.getDestinationType().equals(Queue.class.getName())) { mdbContextOld = null; if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld != null && mdbContext.getDestination() .equals(mdbContextOld.getDestination())) { throw new Exception( "Only one MDB can listen to destination:" + mdbContextOld.getDestination()); } } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Queue queue = (Queue) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Queue=" + queue); } else if (mdbContext.getDestinationType() .equals(Topic.class.getName())) { if (mdbContexts.get(mdbContext.getMdbName()) != null) { mdbContextOld = mdbContexts.get(mdbContext.getMdbName()); if (mdbContextOld.getConsumer() != null) mdbContextOld.getConsumer().setMessageListener(null); if (mdbContextOld.getSession() != null) mdbContextOld.getSession().close(); if (mdbContextOld.getConnection() != null) mdbContextOld.getConnection().close(); } mdbContexts.put(mdbContext.getMdbName(), mdbContext); Topic topic = (Topic) jms.lookup(mdbContext.getDestination()); Connection connection = connectionFactory .createConnection("guest", "guest"); connection.start(); Session session; if (mdbContext.getAcknowledgeMode() != null && mdbContext .getAcknowledgeMode().equals("Auto-Acknowledge")) { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } MessageConsumer consumer = session.createConsumer(topic); consumer.setMessageListener( (MessageListener) mdbBean.newInstance()); mdbContext.setConnection(connection); mdbContext.setSession(session); mdbContext.setConsumer(consumer); System.out.println("Topic=" + topic); } } } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } classLoader.close(); } System.out.println(baseFile.getName().getURI() + " Deployed"); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.apache.hadoop.distributedloadsimulator.sls.SLSRunner.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption("inputsls", true, "input sls files"); options.addOption("nodes", true, "input topology"); options.addOption("output", true, "output directory"); options.addOption("trackjobs", true, "jobs to be tracked during simulating"); options.addOption("printsimulation", false, "print out simulation information"); options.addOption("yarnnode", false, "taking boolean to enable rt mode"); options.addOption("distributedmode", false, "taking boolean to enable scheduler mode"); options.addOption("loadsimulatormode", false, "taking boolean to enable load simulator mode"); options.addOption("rtaddress", true, "Resourcetracker address"); options.addOption("rmaddress", true, "Resourcemanager address for appmaster"); options.addOption("parallelsimulator", false, "this is a boolean value to check whether to enable parallel simulator or not"); options.addOption("rmiaddress", true, "Run a simulator on distributed mode, so we need rmi address"); options.addOption("stopappsimulation", false, "we can stop the application simulation"); options.addOption("isLeader", false, "leading slsRunner for the measurer"); options.addOption("simulationDuration", true, "duration of the simulation only needed by the leader"); options.addOption("rmiport", true, "port for the rmi server"); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); String inputSLS = cmd.getOptionValue("inputsls"); String output = cmd.getOptionValue("output"); String rtAddress = cmd.getOptionValue("rtaddress"); // we are expecting the multiple rt, so input should be comma seperated String rmAddress = cmd.getOptionValue("rmaddress"); String rmiAddress = "127.0.0.1"; boolean isLeader = cmd.hasOption("isLeader"); System.out.println(isLeader); long simulationDuration = 0; int rmiPort = 0; if (isLeader) { System.out.println(cmd.getOptionValue("simulationDuration")); simulationDuration = Long.parseLong(cmd.getOptionValue("simulationDuration")) * 1000; }/*from w ww .ja va2 s . c o m*/ if ((inputSLS == null) || output == null) { System.err.println(); System.err.println("ERROR: Missing input or output file"); System.err.println(); System.err.println( "Options: -inputsls FILE,FILE... " + "-output FILE [-nodes FILE] [-trackjobs JobId,JobId...] " + "[-printsimulation]" + "[-distributedrt]"); System.err.println(); System.exit(1); } File outputFile = new File(output); if (!outputFile.exists() && !outputFile.mkdirs()) { System.err.println("ERROR: Cannot create output directory " + outputFile.getAbsolutePath()); System.exit(1); } Set<String> trackedJobSet = new HashSet<String>(); if (cmd.hasOption("trackjobs")) { String trackjobs = cmd.getOptionValue("trackjobs"); String jobIds[] = trackjobs.split(","); trackedJobSet.addAll(Arrays.asList(jobIds)); } String nodeFile = cmd.hasOption("nodes") ? cmd.getOptionValue("nodes") : ""; String inputFiles[] = inputSLS.split(","); if (cmd.hasOption("stopappsimulation")) { stopAppSimulation = true; LOG.warn("Application simulation is disabled!!!!!!"); } if (cmd.hasOption("parallelsimulator")) { // then we need rmi address rmiAddress = cmd.getOptionValue("rmiaddress"); // currently we support only two simulator in parallel } if (cmd.hasOption("rmiport")) { rmiPort = Integer.parseInt(cmd.getOptionValue("rmiport")); } SLSRunner sls = new SLSRunner(inputFiles, nodeFile, output, trackedJobSet, cmd.hasOption("printsimulation"), cmd.hasOption("yarnnode"), cmd.hasOption("distributedmode"), cmd.hasOption("loadsimulatormode"), rtAddress, rmAddress, rmiAddress, rmiPort, isLeader, simulationDuration); if (!cmd.hasOption("distributedmode")) { try { AMNMCommonObject stub = (AMNMCommonObject) UnicastRemoteObject.exportObject(sls, 0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.getRegistry(rmiPort); registry.bind("AMNMCommonObject", stub); LOG.info("HOP :: SLS RMI Server ready on port " + rmiPort); sls.start(); } catch (Exception e) { System.err.println("Server exception: " + e.toString()); e.printStackTrace(); } } else { sls.start(); } }