Exemplo n.º 1
0
  public static Context initContext(String context_url) {

    Context initContext = null;
    try {
      initContext = new InitialContext();
    } catch (NamingException e) {
      System.out.println("ERROR: initContext(): Could not get InitalContext");
      e.printStackTrace();
      Logger logger = Logger.getLogger(DatabaseData.class);
      logger.error("DatabaseData.initContext(): ", e);
    }

    Context ctx = null;
    try {
      ctx = (Context) initContext.lookup(context_url);
    } catch (NamingException e) {
      System.out.println("ERROR: initContext(): Could not init Context");
      e.printStackTrace();
      System.out.println(
          "DatabaseData().initContext() Exiting!!!!! Setup the context: " + context_url);
      Logger logger = Logger.getLogger(DatabaseData.class);
      logger.error("DatabaseData.initContext(): Exiting", e);
      System.exit(1);
    }

    return ctx;
  }
  public void receiveMessage() {
    Properties prop = new Properties();
    prop.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory");
    prop.put(InitialContext.PROVIDER_URL, "tcp://192.168.122.1:3035/");

    try {
      context = new InitialContext(prop);
      factory = (ConnectionFactory) context.lookup("ConnectionFactory");
      destination = (Destination) context.lookup("queue1");

      connection = factory.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      consumer = session.createConsumer(destination);
      connection.start();

      Message message = consumer.receive();
      if (message instanceof ObjectMessage) {
        ObjectMessage object = (ObjectMessage) message;
        System.out.println("Received: " + object.getObject());
      }

    } catch (NamingException e) {
      e.printStackTrace();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (consumer != null) consumer.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (session != null) session.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (connection != null) connection.close();
    } catch (JMSException e) {
      e.printStackTrace();
    }

    try {
      if (context != null) context.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
  public void testGetPersonByIdQueryRemoteService() {
    System.out.println(
        "Transactional support for this test has rollback set to " + this.isDefaultRollback());
    this.setDefaultRollback(true);

    try {
      org.openhie.openempi.service.PersonManagerService pms = Context.getPersonManagerService();
      PersonUtils.createTestPersonTable(pms, TABLE_NAME, "", false, null, false, null, null);

      RemotePersonServiceLocator remotePersonServiceLocator =
          Context.getRemotePersonServiceLocator();

      SecurityService securityService = remotePersonServiceLocator.getSecurityService(ipAddress);
      String sessionKey = securityService.authenticate("admin", "admin");
      System.out.println("Obtained a session key of " + sessionKey);

      PersonQueryService personQueryService = remotePersonServiceLocator.getPersonQueryService();
      Person p = personQueryService.getPersonById(sessionKey, TABLE_NAME, 1L);
      if (p != null) {
        System.out.println("Found person: " + p);
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (ApplicationException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 4
0
  /** Search criteria based on sn(surname) */
  private void searchUsingSubTree() {
    System.out.println("Inside searchUsingSubTree");
    DirContext ctx = LDAPConstants.getLdapContext();
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();
    String[] attributeFilter = {"cn", "givenName"};
    sc.setReturningAttributes(attributeFilter);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "sn=X*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();

        Attribute attr = attrs.get("cn");
        System.out.print("cn : " + attr.get() + "\n");
        attr = attrs.get("givenName");
        System.out.print("givenName: " + attr.get() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 5
0
  private void searchUsingObject() {
    System.out.println("Inside searchUsingObject");
    DirContext ctx = LDAPConstants.getLdapContext();
    // String baseDN = "CN=sindujar,OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org"; //To serach
    // for a particular user
    String baseDN = "OU=Staff,OU=Accounts,O=ibo,DC=adld,DC=ibo,DC=org";
    SearchControls sc = new SearchControls();

    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "objectclass=*";
    // String filter = "(&(sn=R*)(givenName=Sinduja))";   //Examples for search Filters
    // String filter = "(|(sn=R*)(givenName=Sinduja))";

    NamingEnumeration results = null;
    try {
      results = ctx.search(baseDN, filter, sc);
      while (results.hasMore()) {
        SearchResult sr = (SearchResult) results.next();
        System.out.println(sr.toString() + "\n");
        ctx.close();
      }
    } catch (NamingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 6
0
 public void stopService() {
   try {
     (new InitialContext()).unbind(JAVA_NAMESPACE + _jndiName);
   } catch (NamingException namingexception) {
     namingexception.printStackTrace();
   }
 }
Exemplo n.º 7
0
  /**
   * Clear the directory sub-tree starting with the node represented by the supplied distinguished
   * name.
   *
   * @param ctx The DirContext to use for cleaning the tree.
   * @param name the distinguished name of the root node.
   * @throws NamingException if anything goes wrong removing the sub-tree.
   */
  public static void clearSubContexts(DirContext ctx, Name name) throws NamingException {

    NamingEnumeration enumeration = null;
    try {
      enumeration = ctx.listBindings(name);
      while (enumeration.hasMore()) {
        Binding element = (Binding) enumeration.next();
        Name childName = LdapUtils.newLdapName(element.getName());
        childName = LdapUtils.prepend(childName, name);

        try {
          ctx.destroySubcontext(childName);
        } catch (ContextNotEmptyException e) {
          clearSubContexts(ctx, childName);
          ctx.destroySubcontext(childName);
        }
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } finally {
      try {
        enumeration.close();
      } catch (Exception e) {
        // Never mind this
      }
    }
  }
Exemplo n.º 8
0
  @Override
  public int getCountOfImeisRecorded(String userAdmin) throws MSMApplicationException {
    IMEIManager imeiManager = null;

    int qtde = 0;

    try {
      InitialContext initialContext = new InitialContext();
      imeiManager = (IMEIManager) initialContext.lookup("ndg-core/IMEIManagerBean/remote");
    } catch (NamingException e) {
      e.printStackTrace();
    }

    ArrayList<Object> queryResult = listAllUsers(userAdmin, null).getQueryResult();

    ArrayList<UserVO> listUsers = new ArrayList<UserVO>();

    for (Iterator iterator = queryResult.iterator(); iterator.hasNext(); ) {
      UserVO object = (UserVO) iterator.next();
      listUsers.add(object);
    }

    for (UserVO userVO : listUsers) {
      qtde += imeiManager.findImeiByUser(userVO.getUsername(), null, true).getQueryResult().size();
    }

    return qtde;
  }
Exemplo n.º 9
0
  public void initEJB() {
    try {
      InputStream inputStream =
          this.getClass()
              .getClassLoader()
              .getResourceAsStream("hu/neuron/java/sales/services/Settings.properties");

      Properties properties = new Properties();

      try {
        properties.load(inputStream);
      } catch (IOException e) {
        e.printStackTrace();
      }

      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
      env.put(Context.SECURITY_PRINCIPAL, properties.getProperty("SECURITY_PRINCIPAL"));
      env.put(Context.SECURITY_CREDENTIALS, properties.getProperty("SECURITY_CREDENTIALS"));
      env.put(Context.PROVIDER_URL, properties.getProperty("PROVIDER_URL"));
      Context ctx;

      ctx = new InitialContext(env);
      System.out.println("ctx  = " + ctx);
      offerService =
          (OfferServiceRemote)
              ctx.lookup("OfferService#hu.neuron.java.sales.service.OfferServiceRemote");
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 10
0
 @Override
 public void contextInitialized(ServletContextEvent event) {
   try {
     Context ctx = new InitialContext();
     dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/dataDS");
   } catch (NamingException e) {
     e.printStackTrace();
   }
   try (Connection conn = dataSource.getConnection()) {
     String ddl =
         "CREATE TABLE IF NOT EXISTS TREEITEMS ( ID VARCHAR(30) PRIMARY KEY, PARENT VARCHAR(30),"
             + "URL VARCHAR(255), NAME VARCHAR(255), OWNER VARCHAR(10), UPDATED TIMESTAMP, PRIORITY INT);"
             + "CREATE TABLE IF NOT EXISTS PRODUCTS ( ID VARCHAR(30) PRIMARY KEY, SOURCE VARCHAR(30),"
             + "DESCR VARCHAR(255), PRICE INT, OLDPRICE INT);";
     // TODO add ord column creation to "create table" statament
     // here we modify existing table
     ddl += "ALTER TABLE TREEITEMS ADD COLUMN IF NOT EXISTS ORD INTEGER;";
     try (PreparedStatement ps = conn.prepareStatement(ddl)) {
       ps.execute();
     }
   } catch (SQLException e) {
     System.out.println(e.getMessage());
     e.printStackTrace();
   }
   // if (dataSource != null){
   // System.out.println("Datasource resource injected!");
   // } else {
   // System.out.println("Datasource is null");
   // }
   scheduler = Executors.newSingleThreadScheduledExecutor();
   // scheduler.scheduleAtFixedRate(new UpdateCounts(), 0, 4, TimeUnit.SECONDS);
   scheduler.scheduleAtFixedRate(new PriceDownloader(), 0, 30, TimeUnit.SECONDS);
 }
Exemplo n.º 11
0
  public static void main(String[] args) {

    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.FSContextFactory");
    props.put(Context.PROVIDER_URL, "file:///");

    try {
      Context ctx = new InitialContext(props);
      System.out.println("Contexto obetido com sucesso");

      if (args[1].equals("-t")) {
        buscaTodosArquivo(ctx, 1, args[0]);
      }

      if (args[1].equals("-p")) {
        buscaArquivo(ctx, 1, args[0]);
      }

    } catch (NamingException e) {
      e.printStackTrace();
    }

    if (!achou) {
      System.out.println("não encontrou");
    }

    System.out.println("Finalizou");
  }
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String[] ssns, multipliers;
    Bonus[] bonuses = null;

    log.debug("Getting params from HTTP request");
    ssns = req.getParameterValues("ssn");
    multipliers = req.getParameterValues("multiplier");

    log.debug("Constucting multiple bonuses ...");
    try {
      bonuses = getBonuses(ssns, multipliers);
      for (Bonus bonus : bonuses) {
        log.debug(bonus);
      }

    } catch (NamingException e) {
      e.printStackTrace();
      // log.error(e.getMessage());

    } finally {
      req.setAttribute("bonuses", bonuses);
      log.debug("Finished. Dispatch to result.jsp");
      req.getRequestDispatcher("/multiple-result.jsp").forward(req, resp);
    }
  }
Exemplo n.º 13
0
  public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    // Authenticate as S. User and password "mysecret"
    env.put(Context.SECURITY_AUTHENTICATION, "custom");
    env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial");
    env.put(Context.SECURITY_CREDENTIALS, "mysecret");

    try {
      // Create initial context
      DirContext ctx = new InitialDirContext(env);

      System.out.println(ctx.lookup("ou=NewHires"));

      // do something useful with ctx

      // Close the context when we're done
      ctx.close();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
  protected Map<String, ArrayList<String>> convertAttributes(
      NamingEnumeration<? extends Attribute> attributesEnumeration) {
    Map<String, ArrayList<String>> userInfo = new HashMap<String, ArrayList<String>>();
    try {
      while (attributesEnumeration.hasMore()) {
        Attribute attr = attributesEnumeration.next();
        String id = attr.getID();

        ArrayList<String> values = userInfo.get(id);
        if (values == null) {
          values = new ArrayList<String>();
          userInfo.put(id, values);
        }

        // --- loop on all attribute's values
        NamingEnumeration<?> valueEnum = attr.getAll();

        while (valueEnum.hasMore()) {
          Object value = valueEnum.next();
          // Only retrieve String attribute
          if (value instanceof String) {
            values.add((String) value);
          }
        }
      }
    } catch (NamingException e) {
      e.printStackTrace();
    }
    return userInfo;
  }
Exemplo n.º 15
0
  public void update(String username, String password) {

    try {
      connect();

      System.out.println("Updating...");
      ModificationItem[] mods = new ModificationItem[1];
      Attribute attr = new BasicAttribute("userPassword", password);

      // Support add, replace and remove an attribute.
      mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
      ds.modifyAttributes("uid=" + username + "," + LDAP_BASE, mods);
      System.out.println("Updated.");

    } catch (Exception e) {
      // TODO: handle exception
    } finally {
      try {
        close();
      } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 16
0
 public PoolManager() {
   try {
     ds = (DataSource) context.lookup("java:comp/env/jdbc/androidsds");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 17
0
  private Object getResults(Attribute attr, Object obj) {
    try {
      String name = attr.getID().toString();
      String Value = attr.get().toString();
      Class class1 = obj.getClass();
      String methodName =
          "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
      String[] methodnameIgnot = {"-"};
      for (String ignore : methodnameIgnot) {
        methodName = methodName.replaceAll(ignore, "");
      }
      Method method = class1.getMethod(methodName, String.class);

      String value = (String) method.invoke(obj, Value);

    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return obj;
  }
Exemplo n.º 18
0
  static {
    Context initContext = null;

    try {
      initContext = new InitialContext();
      Context envContext = (Context) initContext.lookup("java:/comp/env");

      datasource = (DataSource) envContext.lookup("jdbc/QAHUB");

    } catch (NamingException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }

    //        Connection conn = ds.getConnection();
    //
    //
    // inStream=ConnectionSource.class.getClass().getResourceAsStream("/dbcpConfig.properties");
    //        pro=new Properties();
    //
    //        try {
    //            pro.load(inStream);
    //            datasource=BasicDataSourceFactory.createDataSource(pro);
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //            throw new RuntimeException("DataSource Initialization Exception");
    //        }
  }
  @Override
  public void setUp() throws SetupException {
    InitialContext initContext = null;
    try {
      initContext = new InitialContext();
      String openid =
          (String) initContext.lookup("java:global/zanata/security/auth-policy-names/openid");

      if (openid != null) {
        dbAuthType = "OPENID";
      } else {
        dbAuthType = "OTHER";
      }
    } catch (NameNotFoundException e) {
      dbAuthType = "OTHER";
    } catch (NamingException e) {
      throw new SetupException(e);
    } finally {
      if (initContext != null) {
        try {
          initContext.close();
        } catch (NamingException e) {
          e.printStackTrace();
        }
      }
    }
  }
Exemplo n.º 20
0
  public QLender(String queuecf, String requestQueue) {
    try {
      // Connect to the provider and get the JMS connection
      Context ctx = new InitialContext();
      QueueConnectionFactory qFactory = (QueueConnectionFactory) ctx.lookup(queuecf);
      qConnect = qFactory.createQueueConnection();

      // Create the JMS Session
      qSession = qConnect.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

      // Lookup the request queue
      requestQ = (Queue) ctx.lookup(requestQueue);

      // Now that setup is complete, start the Connection
      qConnect.start();

      // Create the message listener
      QueueReceiver qReceiver = qSession.createReceiver(requestQ);
      qReceiver.setMessageListener(this);

      System.out.println("Waiting for loan requests...");

    } catch (JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    } catch (NamingException jne) {
      jne.printStackTrace();
      System.exit(1);
    }
  }
Exemplo n.º 21
0
  /**
   * This postparses a name, after it has been returned from the jndi operation. It assumes that it
   * has got a jndi <i>CompositeName</i> that needs to be converted to a legal ldap dn (i.e. an ldap
   * <i>CompoundName</i>). If this is *not* the case, there will be trouble...
   *
   * @param name the post jndi operation name.
   * @return the re-formatted version used by the application, as a DN object.
   */
  public Name postParse(String name) {
    /* EMERGENCY HACK
     * (JNDI apparently does not handle terminating spaces correctly - it
     * retains the escape characters, but trims the actual space, resulting
     * in an illegal ldap dn)
     */
    if (name.charAt(name.length() - 1) == '\\') {
      name = NameUtility.checkEndSpaces(name);
    }

    try {
      Name cn = new CompositeName(name);
      if (cn.size() == 0) // if the name is empty ...
      return new DN(); // ... just return an empty DN

      return new DN(
          cn.get(
              cn.size()
                  - 1)); // get the last element of the composite name, which will be the ldap
                         // compound name, and init the DN with that.
    } catch (NamingException e) // should never happen :-) (ROTFL)
    {
      log.log(
          Level.WARNING,
          "unexpected error: bad name back from jndi ftn in CBOps.postParse("
              + name
              + ")?\n"
              + e.toString());
      e.printStackTrace();
      // System.exit(-1);
      return new DN(name); // bad server response?  return (possibly) corrupt name anyway...
    }
  }
 public static void initialize() {
   try {
     mic = new MockInitialContext();
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
 private ServerConnection() {
   try {
     ic = new InitialContext();
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 24
0
 /**
  * This will attempt to lookup a mail client
  *
  * @param name the name of the mail client to lookup
  * @return a mail client if one exists in the context, null otherwise
  */
 public MailClient lookup(String name) {
   try {
     return (MailClient) context.lookup(name);
   } catch (NamingException e) {
     e.printStackTrace();
   }
   return null;
 } // end lookup
Exemplo n.º 25
0
 @Before
 public void setUp() {
   try {
     hello = (Hello) ic.lookup("HelloBean/remote");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 26
0
 public GetProd() {
   try {
     Context context = new InitialContext();
     ds = (DataSource) context.lookup("java:comp/env/8691");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 27
0
 /** Constructeur */
 public PostServiceImpl() {
   Context context;
   try {
     context = new InitialContext();
     bean =
         (PostManagerRemote) context.lookup(NameFactory.getName("BlogEAR/PostManagerBean/remote"));
   } catch (NamingException e) {
     e.printStackTrace();
   }
   try {
     context = new InitialContext();
     session =
         (BYOBSessionRemote) context.lookup(NameFactory.getName("BlogEAR/BYOBSessionBean/remote"));
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 28
0
 private ServiceLocater() {
   cache = new HashMap<String, Object>();
   try {
     context = new InitialContext();
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
 public ProductDAOJdbc() {
   try {
     Context ctx = new InitialContext();
     dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/xxx");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 30
0
 public MovieManager() {
   try {
     Context jndi = new InitialContext();
     ds = (DataSource) jndi.lookup("java:comp/env/jdbc/dbd");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }