List of usage examples for java.rmi.registry LocateRegistry createRegistry
public static Registry createRegistry(int port) throws RemoteException
Registry
instance on the local host that accepts requests on the specified port
. From source file:org.viafirma.nucleo.Nucleo.java
/** * Inicializa el nucleo, y este a su vez inicializa todos los mdulos que * dependen de el//from w w w .j av a2s . c o m * */ @Override public void init(ServletContext context) { singleton = this; // 1.- inicializamos el sistema de criptografa // Eliminamos el proveedor para evitar que se solapen si ya existia uno. //Security.removeProvider(new BouncyCastleProvider().getName()); //Security.addProvider(new BouncyCastleProvider()); //log.info("Lista de proveedores disponible:" + Arrays.asList(Security.getProviders())); // 1.- Inicializamos los proveedores criptograficos SecurityProvidersUtils.initProviders(); org.apache.xml.security.Init.init(); // inicializa el sistema de cache para mantener los certificados CacheManager manager = CacheManager.getInstance(); cacheCertificados = new Cache("cacheCertificadosEnUso", 200, false, false, TIEMPO_VIDA_CERTIFICADO, TIEMPO_VIDA_CERTIFICADO); manager.addCache(cacheCertificados); log.debug("Inicializada cache de certificados."); cacheDocumentToSign = new Cache("cacheDocumentoToSign", 100, true, false, TIEMPO_VIDA_DOCUMENT_TO_SIGN, TIEMPO_VIDA_DOCUMENT_TO_SIGN); manager.addCache(cacheDocumentToSign); log.debug("Inicializada cache documentos a firmar ."); // 2.- inicializo el servicio RMI. // creamos un registro propio programticamente // en lugar de utilizar el registro JNDI del servidor de aplicaciones o // el comando rmiregistry para aislar nuestra aplicacin de // incompatibilidades // entre diferentes servidores de aplicaciones. try { rmiRegistry = LocateRegistry.createRegistry(Constantes.PORT_RMI); // creamos la instancia del Servidor ConectorFirmaRMI serverRMI = new ConectorFirmaRMI(); // publicamos el servidor en el registro rmiRegistry.bind(Constantes.NOMBRE_CONECOR_RMI_PUBLICADO, serverRMI); log.info("Avtivado registro RMI. Puerto: " + Constantes.PORT_RMI + ", nombre del servicio: " + Constantes.NOMBRE_CONECOR_RMI_PUBLICADO); // Publicamos el servicio tambien en web } catch (RemoteException e) { // No se puede activar el servicio RMI. log.fatal("No se puede activar el servicio RMI " + e.getMessage(), e); } catch (AlreadyBoundException e) { // El puerto ya esta en uso. log.fatal("El puesto " + Constantes.PORT_RMI + " ya esta en uso por otra aplicacin. No se puede activar el servicio de firma", e); } Properties properties = ConfigUtil.getInstance().readConfigPropertes(); // 3.- iniciamos el sistema de custodia de docuemtos Custodia.init(properties); // 4.- iniciamos las erramientas de QRCode QRCodeUtil.init(properties); // 5.- inicializo el envio de Email. SendMailUtil.init(properties); // Configuracin del sistema de validacin de CRLs. Por defecto la // validacin esta activada. String tempValidacion = (String) properties.get(Constantes.PARAM_VALIDACION_ONLINE); boolean validacionOnline = tempValidacion == null ? true : new Boolean(tempValidacion); ValidadorHandler.init(validacionOnline, properties); validador = ValidadorHandler.getCurrentInstance(); log.debug("Inicializado Validador de certificados. Validacin online en: " + validacionOnline); // Metemos en el contexto de aplicacin todos los parametros de // configuracin for (Object key : properties.keySet()) { context.setAttribute((String) key, properties.get(key)); } // Recuperamos la url pblica: URL_PUBLIC_VERIFICATION = properties.getProperty(Constantes.PARAM_URL_APLICACION) + Constantes.PATH_VERIFICACION; log.info("Nucleo Inicializado. "); }
From source file:client.SampleLoginModule.java
/** * <p>//from w w w . j a va 2 s .co m * This method is called if the LoginContext's overall authentication * succeeded (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL * LoginModules succeeded). * * <p> * If this LoginModule's own authentication attempt succeeded (checked by * retrieving the private state saved by the <code>login</code> method), * then this method associates a <code>SamplePrincipal</code> with the * <code>Subject</code> located in the <code>LoginModule</code>. If * this LoginModule's own authentication attempted failed, then this method * removes any state that was originally saved. * * <p> * * @exception LoginException * if the commit fails. * * @return true if this LoginModule's own login and commit attempts * succeeded, or false otherwise. */ public boolean commit() throws LoginException { if (succeeded == false) { return false; } else { // add a Principal (authenticated identity) // to the Subject // assume the user we authenticated is the SamplePrincipal try { LocateRegistry.createRegistry(1099); } catch (Exception e) { System.err.println("Il y a deja un registre de lance"); } ApplicationContext beanFactory = new ClassPathXmlApplicationContext("server_configuration.xml"); userPrincipal = (SamplePrincipal) beanFactory.getBean("idSamplePrincipal"); userPrincipal.setName(username); if (!subject.getPrincipals().contains(userPrincipal)) subject.getPrincipals().add(userPrincipal); if (debug) { System.out.println("\t\t[SampleLoginModule] " + "added SamplePrincipal to Subject"); } // in any case, clean out state username = null; for (int i = 0; i < password.length(); i++) password.toCharArray()[i] = ' '; password = null; commitSucceeded = true; return true; } }
From source file:net.sf.mpaxs.spi.computeHost.Host.java
/** * Erstellt ein RemoteObject vom Typ IRemoteHost und trgt es in die lokale * RMI Registry ein. ber dieses RemoteObject knnen Jobs an diesen * ComputeHoste gesendet werden.//www. j a va 2 s . c o m */ private void getReadyForClients() { Logger.getLogger(Host.class.getName()).log(Level.FINE, "Trying to create registry at {0}:{1}", new Object[] { settings.getLocalIp(), settings.getLocalPort() }); try { LocateRegistry.createRegistry(settings.getLocalPort()); Logger.getLogger(Host.class.getName()).log(Level.FINE, "Started own RMI-Registry on port {0}", settings.getLocalPort()); } catch (RemoteException ex) { if (!settings.getSilentMode()) { Logger.getLogger(Host.class.getName()).log(Level.FINE, "RMI-Registry already running on port {0}.", settings.getLocalPort()); Logger.getLogger(Host.class.getName()).log(Level.FINE, "ComputeHost will use the already running Registry."); } } try { // RemoteObject erstellen IComputeHost remObj = new ComputeHostImpl(this, settings); String bindString = "//" + settings.getLocalIp() + ":" + settings.getLocalPort() + "/" + settings.getName(); Logger.getLogger(Host.class.getName()).log(Level.FINE, "Trying to bind {0}", bindString); Naming.bind(bindString, remObj); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }
From source file:org.hippoecm.repository.RepositoryServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); hippoEventBus = new GuavaHippoEventBus(); HippoServiceRegistry.registerService(hippoEventBus, HippoEventBus.class); listener = new AuditLogger(); HippoServiceRegistry.registerService(listener, HippoEventBus.class); parseInitParameters(config);/*from ww w . ja v a 2s .co m*/ System.setProperty(SYSTEM_SERVLETCONFIG_PROPERTY, repositoryConfig); try { // get the local embedded repository repository = HippoRepositoryFactory.getHippoRepository(storageLocation); HippoRepositoryFactory.setDefaultRepository(repository); if (startRemoteServer) { // the the remote repository RepositoryUrl url = new RepositoryUrl(bindingAddress); rmiRepository = new ServerServicingAdapterFactory(url) .getRemoteRepository(repository.getRepository()); System.setProperty("java.rmi.server.useCodebaseOnly", "true"); // Get or start registry and bind the remote repository try { registry = LocateRegistry.getRegistry(url.getHost(), url.getPort()); registry.rebind(url.getName(), rmiRepository); // connection exception happens here log.info("Using existing rmi server on " + url.getHost() + ":" + url.getPort()); } catch (ConnectException e) { registry = LocateRegistry.createRegistry(url.getPort()); registry.rebind(url.getName(), rmiRepository); log.info("Started an RMI registry on port " + url.getPort()); registryIsEmbedded = true; } } HippoServiceRegistry.registerService(repositoryService = (RepositoryService) repository.getRepository(), RepositoryService.class); HippoServiceRegistry.registerService(repositoryClusterService = new RepositoryClusterService() { @Override public boolean isExternalEvent(final Event event) { if (!(event instanceof JackrabbitEvent)) { throw new IllegalArgumentException("Event is not an instance of JackrabbitEvent"); } return ((JackrabbitEvent) event).isExternal(); } }, RepositoryClusterService.class); } catch (MalformedURLException ex) { log.error("MalformedURLException exception: " + bindingAddress, ex); throw new ServletException("RemoteException: " + ex.getMessage()); } catch (RemoteException ex) { log.error("Generic remoting exception: " + bindingAddress, ex); throw new ServletException("RemoteException: " + ex.getMessage()); } catch (RepositoryException ex) { log.error("Error while setting up JCR repository: ", ex); throw new ServletException("RepositoryException: " + ex.getMessage()); } freeMarkerConfiguration = createFreemarkerConfiguration(); }
From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); parseInitParameters(config);//from w w w. ja va 2s .co m System.setProperty(SYSTEM_SERVLETCONFIG_PROPERTY, repositoryConfig); try { // get the local embedded repository repository = HippoRepositoryFactory.getHippoRepository(storageLocation); HippoRepositoryFactory.setDefaultRepository(repository); if (startRemoteServer) { // the the remote repository RepositoryUrl url = new RepositoryUrl(bindingAddress); rmiRepository = new ServerServicingAdapterFactory(url) .getRemoteRepository(repository.getRepository()); System.setProperty("java.rmi.server.useCodebaseOnly", "true"); // Get or start registry and bind the remote repository try { registry = LocateRegistry.getRegistry(url.getHost(), url.getPort()); registry.rebind(url.getName(), rmiRepository); // connection exception // happens here log.info("Using existing rmi server on " + url.getHost() + ":" + url.getPort()); } catch (ConnectException e) { registry = LocateRegistry.createRegistry(url.getPort()); registry.rebind(url.getName(), rmiRepository); log.info("Started an RMI registry on port " + url.getPort()); registryIsEmbedded = true; } } repositoryService = HippoServiceRegistry.getService(RepositoryService.class); if (repositoryService == null) { HippoServiceRegistry.registerService( repositoryService = (RepositoryService) repository.getRepository(), RepositoryService.class); } repositoryClusterService = HippoServiceRegistry.getService(RepositoryClusterService.class); if (repositoryClusterService == null) { HippoServiceRegistry.registerService(repositoryClusterService = new RepositoryClusterService() { @Override public boolean isExternalEvent(final Event event) { if (!(event instanceof JackrabbitEvent)) { throw new IllegalArgumentException("Event is not an instance of JackrabbitEvent"); } return ((JackrabbitEvent) event).isExternal(); } }, RepositoryClusterService.class); } } catch (MalformedURLException ex) { log.error("MalformedURLException exception: " + bindingAddress, ex); throw new ServletException("RemoteException: " + ex.getMessage()); } catch (RemoteException ex) { log.error("Generic remoting exception: " + bindingAddress, ex); throw new ServletException("RemoteException: " + ex.getMessage()); } catch (RepositoryException ex) { log.error("Error while setting up JCR repository: ", ex); throw new ServletException("RepositoryException: " + ex.getMessage()); } freeMarkerConfiguration = createFreemarkerConfiguration(); }
From source file:org.mule.module.management.agent.AbstractJmxAgent.java
protected void initRMI() throws Exception { String connectUri = (connectorServerUrl != null ? connectorServerUrl : StringUtils.EMPTY); if (connectUri.contains("jmx:rmi")) { int i = connectUri.lastIndexOf("rmi://"); URI uri = new URI(connectUri.substring(i)); if (rmiRegistry == null) { try { if (isCreateRmiRegistry()) { try { rmiRegistry = LocateRegistry.createRegistry(uri.getPort()); } catch (ExportException e) { logger.info("Registry on " + uri + " already bound. Attempting to use that instead"); rmiRegistry = LocateRegistry.getRegistry(uri.getHost(), uri.getPort()); }/* w ww . j av a2s.c om*/ } else { rmiRegistry = LocateRegistry.getRegistry(uri.getHost(), uri.getPort()); } } catch (RemoteException e) { throw new InitialisationException(e, this); } } } }
From source file:org.act.index.server.MetaService.java
public int createCoreWithNoSegment(int coreId) { // TODO Auto-generated method stub try {// w w w .j a v a 2 s. co m if (indexServer.getSolrServers().containsKey(coreId)) return GlobalMessage.ISS_ERROR; String dir = indexServer.getUrl() + "/core" + String.valueOf(coreId); //LOG.debug("dir:" + dir); indexServer.addSolrServer(coreId); FileUtils.forceMkdir(new File(dir)); FileUtils.forceMkdir(new File(dir + "/conf")); String configPath = dir + "/conf/solrconfig.xml"; String schemaPath = dir + "/conf/schema.xml"; createSolrConfig(configPath); createSchema(schemaPath, coreId); //indexServer.addSolrServer(coreId); //CoreAdminRequest.createCore(String.valueOf(coreId), "core" // + String.valueOf(coreId), indexServer.getSolrServer()); CoreAdminRequest.createCore(String.valueOf(coreId), "core" + String.valueOf(coreId), indexServer.getSolrServer()); //CoreAdminRequest.createCore("10", "core10", server, configPath, schemaPath); //FileUtils.forceMkdir(new File(dir + "/data")); //FileUtils.forceMkdir(new File(dir + "/data/index")); FileUtils.cleanDirectory(new File(dir + "/data/index")); SolrService service = new SolrService(indexServer.getSolrServer(coreId)); //solrServices.put(coreId, service); //int port = ServerParam.LOCAL_SERVER_PORT + serverId * ServerParam.MAX_CORE_COUNT_PER_SERVER + coreId + 1; int serverId = indexServer.getServerInfo().getServerId(); String ip = Inet4Address.getLocalHost().getHostAddress(); int port = indexServer.getServerAddr().getPort() + coreId + 1; LocateRegistry.createRegistry(port); String name = "rmi://" + ip + ":" + port + "/core" + coreId + "@server" + serverId; Naming.rebind(name, service); LOG.info("rmi:solrserver( " + name + ") is ready!"); } catch (SolrServerException e) { // TODO: handle exception e.printStackTrace(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } return GlobalMessage.ISS_SUCCESS; }
From source file:org.springframework.remoting.rmi.RmiRegistryFactoryBean.java
/** * Locate or create the RMI registry.// w ww . jav a2 s . c o m * @param registryPort the registry port to use * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(int registryPort) throws RemoteException { if (this.alwaysCreate) { logger.info("Creating new RMI registry"); this.created = true; return LocateRegistry.createRegistry(registryPort); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "'"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(registryPort); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. this.created = true; return LocateRegistry.createRegistry(registryPort); } } }
From source file:org.red5.server.jmx.JMXAgent.java
public void init() { //environmental var holder HashMap env = null;/*from www . ja v a 2 s. c o m*/ if (enableHtmlAdapter) { // setup the adapter try { //instance an html adaptor int port = htmlAdapterPort == null ? 8082 : Integer.valueOf(htmlAdapterPort); html = new HtmlAdaptorServer(port); ObjectName htmlName = new ObjectName( JMXFactory.getDefaultDomain() + ":type=HtmlAdaptorServer,port=" + port); log.debug("Created HTML adaptor on port: " + port); //add the adaptor to the server mbs.registerMBean(html, htmlName); //start the adaptor html.start(); log.info("JMX HTML connector server successfully started"); } catch (Exception e) { log.error("Error in setup of JMX subsystem (HTML adapter)", e); } } else { log.info("JMX HTML adapter was not enabled"); } if (enableRmiAdapter) { // Create an RMI connector server log.debug("Create an RMI connector server"); try { Registry r = null; try { //lookup the registry r = LocateRegistry.getRegistry(Integer.valueOf(rmiAdapterPort)); //ensure we are not already registered with the registry for (String regName : r.list()) { if (regName.equals("red5")) { //unbind connector from rmi registry r.unbind("red5"); } } } catch (RemoteException re) { log.info("RMI Registry server was not found on port " + rmiAdapterPort); //if we didnt find the registry and the user wants it created if (startRegistry) { log.info("Starting an internal RMI registry"); // create registry for rmi port 9999 r = LocateRegistry.createRegistry(Integer.valueOf(rmiAdapterPort)); } } JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + rmiAdapterPort + "/red5"); //if SSL is requested to secure rmi connections if (enableSsl) { // Environment map log.debug("Initialize the environment map"); env = new HashMap(); // Provide SSL-based RMI socket factories SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory(); SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(); env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf); } //if authentication is requested if (StringUtils.isNotBlank(remoteAccessProperties)) { //if ssl is not used this will be null if (null == env) { env = new HashMap(); } //check the existance of the files //in the war version the full path is needed File file = new File(remoteAccessProperties); if (!file.exists()) { log.debug("Access file was not found on path, will prepend config_root"); //pre-pend the system property set in war startup remoteAccessProperties = System.getProperty("red5.config_root") + '/' + remoteAccessProperties; remotePasswordProperties = System.getProperty("red5.config_root") + '/' + remotePasswordProperties; } env.put("jmx.remote.x.access.file", remoteAccessProperties); env.put("jmx.remote.x.password.file", remotePasswordProperties); } // create the connector server cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs); // add a listener for shutdown cs.addNotificationListener(this, null, null); // Start the RMI connector server log.debug("Start the RMI connector server"); cs.start(); log.info("JMX RMI connector server successfully started"); } catch (ConnectException e) { log.warn("Could not establish RMI connection to port " + rmiAdapterPort + ", please make sure \"rmiregistry\" is running and configured to listen on this port."); } catch (IOException e) { String errMsg = e.getMessage(); if (errMsg.indexOf("NameAlreadyBoundException") != -1) { log.error("JMX connector (red5) already registered, you will need to restart your rmiregistry"); } else { log.error("{}", e); } } catch (Exception e) { log.error("Error in setup of JMX subsystem (RMI connector)", e); } } else { log.info("JMX RMI adapter was not enabled"); } }
From source file:org.quartz.core.QuartzScheduler.java
/** * <p>/*from w w w. j a va 2s . com*/ * Bind the scheduler to an RMI registry. * </p> */ private void bind() throws RemoteException { String host = resources.getRMIRegistryHost(); // don't export if we're not configured to do so... if (host == null || host.length() == 0) { return; } RemotableQuartzScheduler exportable = null; if (resources.getRMIServerPort() > 0) { exportable = (RemotableQuartzScheduler) UnicastRemoteObject.exportObject(this, resources.getRMIServerPort()); } else { exportable = (RemotableQuartzScheduler) UnicastRemoteObject.exportObject(this); } Registry registry = null; if (resources.getRMICreateRegistryStrategy().equals(QuartzSchedulerResources.CREATE_REGISTRY_AS_NEEDED)) { try { // First try to get an existing one, instead of creating it, // since if // we're in a web-app being 'hot' re-depoloyed, then the JVM // still // has the registry that we created above the first time... registry = LocateRegistry.getRegistry(resources.getRMIRegistryPort()); registry.list(); } catch (Exception e) { registry = LocateRegistry.createRegistry(resources.getRMIRegistryPort()); } } else if (resources.getRMICreateRegistryStrategy() .equals(QuartzSchedulerResources.CREATE_REGISTRY_ALWAYS)) { try { registry = LocateRegistry.createRegistry(resources.getRMIRegistryPort()); } catch (Exception e) { // Fall back to an existing one, instead of creating it, since // if // we're in a web-app being 'hot' re-depoloyed, then the JVM // still // has the registry that we created above the first time... registry = LocateRegistry.getRegistry(resources.getRMIRegistryPort()); } } else { registry = LocateRegistry.getRegistry(resources.getRMIRegistryHost(), resources.getRMIRegistryPort()); } String bindName = resources.getRMIBindName(); registry.rebind(bindName, exportable); getLog().info("Scheduler bound to RMI registry under name '" + bindName + "'"); }