En esta página: Seguir Remisiones Manualmente Si hemos configurado la propiedad de entorno Context.REFERRAL como "throw", toda remisión encontrada resultará en una ReferralException. Una ReferralException contiene información de remisión--información que describe la remisión (como una lista de URLs)-- y un contexto de remisión--el contexto al que se refiere la remisión. Aquí están los pasos que normalmente sigue un programa cuando maneja remisiones manualmente:
Aquí tenemos un ejemplo. // Set the referral property to throw ReferralException env.put(Context.REFERRAL, "throw"); // Create the initial context DirContext ctx = new InitialDirContext(env); // Set the controls for performing a subtree search SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Do this in a loop because you don't know how // many referrals there will be for (boolean moreReferrals = true; moreReferrals;) { try { // Perform the search NamingEnumeration answer = ctx.search("", "(objectclass=*)", ctls); // Print the answer while (answer.hasMore()) { System.out.println(">>>" + ((SearchResult)answer.next()).getName()); } // The search completes with no more referrals moreReferrals = false; } catch (ReferralException e) { if (! followReferral(e.getReferralInfo())) { moreReferrals = e.skipReferral(); } // Point to the new context if (moreReferrals) { ctx = (DirContext) e.getReferralContext(); } } } Para los métodos que devuelven una enumeración, como Context.list() o DirContext.search(), debemos situar el bloque try/catch para la ReferralException alrededor de la llamada inicial y del bucle while que itera sobre los resultados. Cuando se lanza la ReferralException, la enumeración existente se convierte en no válida y debemos re-llamar al método de contexto original y obtener una nueva enumeración. Observa también, que el bucle exterior encierra tanto la llamada al método sobre el contexto como la iteracción sobre los resultados. Autentificando en un Contexto Remitido Por defecto, cuando llamados a ReferralException.getReferralContext(), el método usa las propiedades de entorno del contexto original, incluyendo las propiedades relacionadas con la seguridad, para crear una conexión con el servidor remitido. Algunas veces, para examinar la información de remisión podríamos querer seguir la remisión usando una información de autentificación diferente. Podemos hacer esto usando ReferralException.getReferralContext(env). ... } catch (ReferralException e) { ... env.put(Context.SECURITY_PRINCIPAL, "newuser"); env.put(Context.SECURITY_CREDENTIALS, "newpasswd"); ctx = e.getReferralContext(env); } Si falla la autentificación, es decir, getReferralContext(env) lanza una excepción, podemos intentarlo primero llamando a ReferralException.retryReferral() y luego repitiendo la llamada a getReferralContext(env) con las propiedades de entorno actualizadas. Si no queremos reintentarlo, llamamos a ReferralException.skipReferral() antes de llamar a getReferralContext(env). Aquí tenemos un ejemplo: ... } catch (ReferralException e) { if (!ask("Follow referral " + e.getReferralInfo())) { moreReferrals = e.skipReferral(); } else { // Get credentials for the referral being followed getCreds(env); } // Do this in a loop in case getReferralContext() // fails with bad authentication info. while (moreReferrals) { try { ctx = (DirContext)e.getReferralContext(env); break; // Success: got context } catch (AuthenticationException ne) { if (ask("Authentication failed. Retry")) { getCreds(env); e.retryReferral(); } else { // Give up and go on to the next referral moreReferrals = e.skipReferral(); } } catch (NamingException ne) { System.out.println("Referral failed: " + ne); // Give up and go on to the next referral moreReferrals = e.skipReferral(); } } } En este ejemplo, la llamada a e.getReferralContext(env) está situada dentro de un bucle para que si falla, pueda reintentarlo usando diferentes credenciales. El ejemplo define un método local, getCreds(), para obtener el nombre y las credenciales desde la Entrada Estándar para actualizar la propiedade de entorno, env, que está siendo utilizada para obtener el contexto remitido. Cuando e.getReferralContext(env) falla, el usuario de la aplicación puede eligir entre volver a intentarlo usando diferentes credenciales o saltarse la remisión que falla. Pasar Controles de Solicitud a un Contexto Remitido En la lección Controles y Extensiones puedes encontrar más detalles sobre cómo cambiar controles de solicitud sde un contexto remitido.
|