Esempio n. 1
0
 private static Map<String, DataSource> getJndiDataSourcesAt(String jndiPrefix)
     throws NamingException {
   final InitialContext initialContext = new InitialContext();
   final Map<String, DataSource> dataSources = new LinkedHashMap<String, DataSource>(2);
   try {
     for (final NameClassPair nameClassPair : Collections.list(initialContext.list(jndiPrefix))) {
       // note: il ne suffit pas de tester
       // (DataSource.class.isAssignableFrom(Class.forName(nameClassPair.getClassName())))
       // car nameClassPair.getClassName() vaut "javax.naming.LinkRef" sous jboss 5.1.0.GA
       // par exemple, donc on fait le lookup pour voir
       final String jndiName;
       if (nameClassPair.getName().startsWith("java:")) {
         // pour glassfish v3
         jndiName = nameClassPair.getName();
       } else {
         jndiName = jndiPrefix + '/' + nameClassPair.getName();
       }
       final Object value = initialContext.lookup(jndiName);
       if (value instanceof DataSource) {
         dataSources.put(jndiName, (DataSource) value);
       }
     }
   } catch (final NamingException e) {
     // le préfixe ("comp/env/jdbc", "/jdbc" ou "java:global/jdbc", etc) n'existe pas dans jndi,
     // (dans glassfish 3.0.1, c'est une NamingException et non une NameNotFoundException)
     return dataSources;
   }
   initialContext.close();
   return dataSources;
 }
  /**
   * List children of this collection. The names given are relative to this URI's path. The full uri
   * of the children is then : path + "/" + name.
   */
  public Enumeration<String> list() throws IOException {

    if (!connected) {
      connect();
    }

    if ((resource == null) && (collection == null)) {
      throw new FileNotFoundException(getURL() == null ? "null" : getURL().toString());
    }

    Vector<String> result = new Vector<String>();

    if (collection != null) {
      try {
        NamingEnumeration<NameClassPair> enumeration = collection.list("/");
        while (enumeration.hasMoreElements()) {
          NameClassPair ncp = enumeration.nextElement();
          String s = ncp.getName();
          result.addElement(URL_ENCODER.encodeURL(s, 0, s.length()).toString());
        }
      } catch (NamingException e) {
        // Unexpected exception
        throw new FileNotFoundException(getURL() == null ? "null" : getURL().toString());
      }
    }

    return result.elements();
  }
 public boolean hasChildren(Object node) {
   NameClassPair ncp = (NameClassPair) node;
   String nm = ncp.getName();
   if (nm.equals("")) // root node
   return true;
   return ncp.getClassName().equals(CLASS_WITH_CHILDREN);
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testRunning() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

    HashSet set = new HashSet();

    NamingEnumeration list = ctx.list("ou=system");

    while (list.hasMore()) {
      NameClassPair ncp = (NameClassPair) list.next();
      set.add(ncp.getName());
    }

    assertTrue(set.contains("uid=admin"));
    assertTrue(set.contains("ou=users"));
    assertTrue(set.contains("ou=groups"));
    assertTrue(set.contains("ou=configuration"));
    assertTrue(set.contains("prefNodeName=sysPrefRoot"));
  }
  @Test
  public void testIt() throws Exception {
    final InitialContext ctx = getRemoteContext();
    final ClassLoader current = Thread.currentThread().getContextClassLoader();

    try {
      Thread.currentThread().setContextClassLoader(Remote.class.getClassLoader());

      Remote remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME + "/" + Bean.class.getSimpleName() + "!" + Remote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME
                      + "/"
                      + Singleton.class.getSimpleName()
                      + "!"
                      + BinderRemote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME
                      + "/"
                      + StatefulBean.class.getSimpleName()
                      + "!"
                      + Remote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      final Set<String> expected = new HashSet<String>();
      expected.add(Bean.class.getSimpleName() + "!" + Remote.class.getName());
      expected.add(Singleton.class.getSimpleName() + "!" + BinderRemote.class.getName());
      expected.add(StatefulBean.class.getSimpleName() + "!" + Remote.class.getName());

      NamingEnumeration<NameClassPair> e = ctx.list("test");
      while (e.hasMore()) {
        NameClassPair binding = e.next();
        if (!expected.remove(binding.getName())) {
          Assert.fail("unknown binding " + binding.getName());
        }
      }
      if (!expected.isEmpty()) {
        Assert.fail("bindings not found " + expected);
      }

    } finally {
      ctx.close();
      Thread.currentThread().setContextClassLoader(current);
    }
  }
  /** Returns child <code>TreeNode</code>s for the given <code>TreeNode</code> model Object. */
  public List getChildTreeNodeObjects(Object nodeObject) {
    if (nodeObject == null) {
      return null;
    }
    // if (nodeObject.toString().equals(_objectName)) {
    // In this implementation _objectName represents the top-level,
    // we need to find its children here
    // if (_children != null) {
    //    return Arrays.asList((Object[])_children);
    // }

    String context = "";
    if (nodeObject instanceof NameClassPair) {

      context = (String) ((NameClassPair) nodeObject).getName();
      _nodeClass = (String) ((NameClassPair) nodeObject).getClassName();
    }

    List transformed = new ArrayList();
    try {
      ArrayList result =
          (ArrayList)
              JMXUtil.getMBeanServer()
                  .invoke(
                      new ObjectName(_objectName),
                      "getNames",
                      new String[] {context},
                      new String[] {"java.lang.String"});
      for (int i = 0; i < result.size(); i++) {
        NameClassPair pair = (NameClassPair) result.get(i);
        String nm = pair.getName();
        String prepend = context.equals("") ? "" : context + "/";
        pair.setName(prepend + pair.getName());
        transformed.add(pair);
      }
      _children = transformed.toArray(new Object[0]);

      // Ok, we got the result, provide an event in case we want to
      // do some filtering
      FacesContext ctx = FacesContext.getCurrentInstance();
      Object retVal =
          getLayoutComponent()
              .dispatchHandlers(
                  ctx,
                  FilterTreeEvent.EVENT_TYPE,
                  new FilterTreeEvent(getParentUIComponent(), _children));
      if ((retVal != null) && (retVal instanceof Object[])) {
        // We have a return value, use it instead of the original list
        _children = (Object[]) retVal;
      }
    } catch (Exception ex) {
      // Ignore exception since there are no children
      _children = null;
    }

    return _children != null ? Arrays.asList((Object[]) _children) : null;
  }
 private static void dumpTreeEntry(NamingEnumeration<NameClassPair> list, String s)
     throws NamingException {
   System.out.println("\ndump " + s);
   while (list.hasMore()) {
     NameClassPair ncp = list.next();
     System.out.println(ncp.toString());
     if (s.length() == 0) {
       dumpJndi(ncp.getName());
     } else {
       dumpJndi(s + "/" + ncp.getName());
     }
   }
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String infoString = "";
    String listString = "";
    logger.info("zzzzzzzzzzzzzzzzzzzzzzzzzzz beginning run");

    try {
      Context initCtx = new InitialContext();
      Context envCtx = (Context) initCtx.lookup("java:comp/env");
      Object oo = envCtx.lookup("jms/ConnectionFactory");
      if (oo != null) {
        infoString += "<h4>Sample lookup: " + oo.getClass().getName() + "</h4>";
      }
      NamingEnumeration<NameClassPair> nameInfo = envCtx.list("jms");
      while (nameInfo.hasMore()) {
        NameClassPair n = nameInfo.next();
        listString += "<li>" + n.getClassName() + " -- " + n.getName() + "</li>";
      }
      Queue tomcatQueue = (Queue) envCtx.lookup("jms/TomcatQueue");
      infoString += "<h4>Tomcat queue: " + tomcatQueue.getQueueName() + "</h4>";
      ActiveMQQueue aQueue = (ActiveMQQueue) tomcatQueue;
      infoString += "<h4>Apache queue: " + aQueue.getDestinationTypeAsString() + "</h4>";

    } catch (Exception ex) {
      String exI = "Error: " + ex.getClass().getName() + "-- " + ex.getMessage();
      logger.error(exI);
      infoString += "Error: <b>" + exI + "</b>";
    }

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet JmsTestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>List of items at java:comp/env/jms</h1>");
    out.println("<p>" + infoString + "</p>");
    out.println("<ol>" + listString + "</ol>");
    out.println("</body>");
    out.println("</html>");
  }
Esempio n. 9
0
  void exploreNext(int depth, DirContext ctx, String path) throws NamingException {
    NamingEnumeration<NameClassPair> names = ctx.list(path);

    while (names.hasMore()) {
      Object obj = names.next();
      NameClassPair ncp = (NameClassPair) obj;
      if (ncp.getClassName().equals("weblogic.jndi.internal.ServerNamingNode")) {
        System.out.println(createBlanks(depth) + ncp.getName());
        exploreNext(depth + 1, ctx, path + "/" + ncp.getName());
      } else {
        System.out.print(createBlanks(depth) + "[" + ncp.getName());
        System.out.print("] - ");
        try {
          // System.out.println(ctx.lookup(path+"/"+ncp.getName()));
          System.out.println(ncp.getClassName());
        } catch (Exception ex) {
          System.out.println("");
        }
      }
    }
  }
Esempio n. 10
0
  public Message list(String base) {
    // "ou=users,dc=dexels,dc=com"
    try {
      if (initialDir == null) {
        startup();
      }
      DirContext dc = (DirContext) initialDir.lookup(base);
      NamingEnumeration e = dc.list("");
      while (e.hasMore()) {
        NameClassPair o = (NameClassPair) e.next();
        logger.info("NAME: " + o.getName());
        logger.info("NAMESp: " + o.getNameInNamespace());
        //				o.getSchema("");
        logger.info("o: " + o);
      }
    } catch (NamingException e) {
      e.printStackTrace();
    }

    return null;
  }
Esempio n. 11
0
  public Collection getEnvProperties(String envSubDir, boolean sortProperties) throws Exception {
    ArrayList envListReturn = new ArrayList();
    try {
      InitialContext EnvironmentContext = new InitialContext();
      NamingEnumeration<NameClassPair> envList =
          EnvironmentContext.list("java:comp/env/" + envSubDir);

      if (envList != null) {
        NameClassPair item;
        while (envList.hasMore()) {
          item = envList.next();
          envListReturn.add(item.getName());
        }
      }
    } catch (NamingException NE) {
      NE.printStackTrace();
      // Eccezione tracciata ma volutamente non rilancia.
      // Nel caso non trovasse variabili definite è corretto che torni una lista vuota.
    }
    if (sortProperties) Collections.sort(envListReturn);
    return envListReturn;
  }
Esempio n. 12
0
  /**
   * This postparses a namingEnumeration of NameClassPairs, after it has been returned from the jndi
   * operation. Usefull to over-ride if the names in the enumeration need to be unescaped or
   * reformatted.
   *
   * @param e the post jndi operation namingEnumeration.
   * @param base the 'base' dn from which the names in the enumeration (may) be relative. If the
   *     Names in the enumeration are suffixed by the searchBase, they are unaltered, otherwise the
   *     searchBase is added to the names to give the full DN in the namespace.
   * @return the re-formatted version used by the application.
   */
  public NamingEnumeration postParseNameClassPairs(NamingEnumeration e, Name base)
      throws NamingException {
    log.log(Level.FINER, "parsing with base :" + base.toString());
    DXNamingEnumeration dxe = new DXNamingEnumeration();

    String baseString = null;

    if (base != null && base.isEmpty() == false) baseString = base.toString();

    try {
      while (e.hasMore()) {
        NameClassPair ncp = (NameClassPair) e.next();

        String rawName = postParseString(ncp.getName()).toString();

        // IMPORTANT!
        // This appends the 'base' DN to the enumerated DNs in order to get absolute DNs...

        if (ncp.isRelative() && baseString != null) {
          if (rawName.length() != 0) rawName = rawName + "," + baseString;
          else rawName = baseString;
        }

        log.log(Level.FINER, "ended up with: '" + rawName + "'");
        ncp.setName(rawName);
        dxe.add(ncp);
      }
    } catch (NamingException ex) {
      CBUtility.error(
          CBIntText.get("Search partially failed! - only ")
              + dxe.size()
              + CBIntText.get(" entries returned."),
          ex);
    }

    return dxe;
  }
Esempio n. 13
0
  /**
   * Recursively display the naming context information into the buffer.
   *
   * @param ctx
   * @param indent
   * @param buffer
   * @param verbose
   */
  public static void list(Context ctx, String indent, StringBuffer buffer, boolean verbose) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {
      NamingEnumeration ne = ctx.list("");
      while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.next();

        String name = pair.getName();
        String className = pair.getClassName();
        boolean recursive = false;
        boolean isLinkRef = false;
        boolean isProxy = false;
        Class c = null;
        try {
          c = loader.loadClass(className);

          if (Context.class.isAssignableFrom(c)) recursive = true;
          if (LinkRef.class.isAssignableFrom(c)) isLinkRef = true;

          isProxy = Proxy.isProxyClass(c);
        } catch (ClassNotFoundException cnfe) {
          // If this is a $Proxy* class its a proxy
          if (className.startsWith("$Proxy")) {
            isProxy = true;
            // We have to get the class from the binding
            try {
              Object p = ctx.lookup(name);
              c = p.getClass();
            } catch (NamingException e) {
              Throwable t = e.getRootCause();
              if (t instanceof ClassNotFoundException) {
                // Get the class name from the exception msg
                String msg = t.getMessage();
                if (msg != null) {
                  // Reset the class name to the CNFE class
                  className = msg;
                }
              }
            }
          }
        }

        buffer.append(indent + " +- " + name);

        // Display reference targets
        if (isLinkRef) {
          // Get the
          try {
            Object obj = ctx.lookupLink(name);

            LinkRef link = (LinkRef) obj;
            buffer.append("[link -> ");
            buffer.append(link.getLinkName());
            buffer.append(']');
          } catch (Throwable t) {
            buffer.append("invalid]");
          }
        }

        // Display proxy interfaces
        if (isProxy) {
          buffer.append(" (proxy: " + pair.getClassName());
          if (c != null) {
            Class[] ifaces = c.getInterfaces();
            buffer.append(" implements ");
            for (int i = 0; i < ifaces.length; i++) {
              buffer.append(ifaces[i]);
              buffer.append(',');
            }
            buffer.setCharAt(buffer.length() - 1, ')');
          } else {
            buffer.append(" implements " + className + ")");
          }
        } else if (verbose) {
          buffer.append(" (class: " + pair.getClassName() + ")");
        }

        buffer.append('\n');
        if (recursive) {
          try {
            Object value = ctx.lookup(name);
            if (value instanceof Context) {
              Context subctx = (Context) value;
              list(subctx, indent + " |  ", buffer, verbose);
            } else {
              buffer.append(indent + " |   NonContext: " + value);
              buffer.append('\n');
            }
          } catch (Throwable t) {
            buffer.append("Failed to lookup: " + name + ", errmsg=" + t.getMessage());
            buffer.append('\n');
          }
        }
      }
      ne.close();
    } catch (NamingException ne) {
      buffer.append("error while listing context " + ctx.toString() + ": " + ne.toString(true));
      formatException(buffer, ne);
    }
  }
  private void initJNDI(Properties properties) throws NamingException {
    if (ctx != null) {
      try {
        ctx.close();
      } catch (NamingException e) {
        //                Utils.printTrace(e);
        throw e;
      }
    }

    //        jndiProps.put("weblogic.jndi.responseReadTimeout", "100");
    try {
      if (properties != null) {
        Hashtable<String, String> jndiProps = null;
        jndiProps = new Hashtable<String, String>();

        jndiProps.put(Context.PROVIDER_URL, properties.getProperty(Context.PROVIDER_URL));
        jndiProps.put(
            Context.SECURITY_CREDENTIALS, properties.getProperty(Context.SECURITY_CREDENTIALS));
        jndiProps.put(
            Context.INITIAL_CONTEXT_FACTORY,
            properties.getProperty(Context.INITIAL_CONTEXT_FACTORY));
        jndiProps.put(
            Context.SECURITY_PRINCIPAL, properties.getProperty(Context.SECURITY_PRINCIPAL));
        jndiProps.put("dicated.connection", "true");
        ctx = new InitialContext(jndiProps);
      } else ctx = new InitialContext();

      Hashtable hashTable = ctx.getEnvironment();
      Utils.printTrace(false);
      Utils.printMessage(hashTable.toString());
    } catch (NamingException e) {
      //            Utils.printTrace(false);
      //            Utils.printTrace(e);
      //            Utils.printMessage("! service stop !");
      throw e;
    }

    // connect to the server
    try {
      NamingEnumeration<NameClassPair> list = null;
      // list all avaiable names
      if (this.appServiceProperties != null
          && "Y"
              .equals(
                  this.appServiceProperties
                      .getProperty("print.all.available.services")
                      .toUpperCase())) {
        Utils.printMessage("=======================================");
        list = ctx.list("");
        while (list.hasMore()) {

          try {
            NameClassPair tt = list.next();
            Object ttt = ctx.lookup(tt.getName());
            Utils.printMessage(ttt.getClass() + ":\t" + tt.getName());
          } catch (Exception e) {
            Utils.printTrace(e);
          }
        }
        Utils.printMessage("=======================================");
      }

      // get user transaction
      userTransaction =
          (UserTransaction) ctx.lookup(RMIIQMAppModuleServicesConstants.RMIUserTransaction);

      // get general app service
      this.appModuleService =
          ctx.lookup(RMIIQMAppModuleServicesConstants.appModuleGeneralServiceName);
      // get lookup service
      this.appModuleLookupService =
          ctx.lookup(RMIIQMAppModuleServicesConstants.appModuleLookupServiceName);
      // get non temporal service
      this.appModuleNonTemporalService =
          ctx.lookup(RMIIQMAppModuleServicesConstants.appModuleNonTemporalServiceName);

      if (this.appServiceProperties != null
          && "Y"
              .equals(
                  this.appServiceProperties
                      .getProperty("print.service.available.methods")
                      .toUpperCase())) {
        Utils.printMessage("================ this.appModuleService ================");
        Utils.printMethods(this.appModuleService);
        Utils.printMessage("================ this.appModuleLookupService ================");
        Utils.printMethods(this.appModuleLookupService);
        Utils.printMessage("================ this.appModuleNonTemporalService ================");
        Utils.printMethods(this.appModuleNonTemporalService);
      }

    } catch (Exception e) {
      Utils.printTrace(e);
      Utils.printMessage(e);
      throw e;
    }
  }