/**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Returns a
   * <code>java.util.List<String></code> with the Distinguished names of the entries that match. You
   * can specify a match limit
   *
   * @param q DirectoryQuery
   * @param limit An <code>Integer</code> with the limit of matches
   * @return List<String>
   * @exception LDAPException
   */
  public List<String> searchDN(final LDAPDirectoryQuery q, final Integer limit)
      throws LDAPException {
    List<String> results = new ArrayList<String>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      if (limit != null) {
        ctls.setCountLimit(limit.intValue());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        results.add(sr.getNameInNamespace());
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() null pointer");
      throw new LDAPException("search DN null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "searchDN() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
  public static InitialDirContext createDirectoryContext(
      LDAPConfigurator ldapConfigurator, String principal, String credentials) {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfigurator.getInitialContextFactory());
    properties.put(
        Context.PROVIDER_URL, ldapConfigurator.getServer() + ":" + ldapConfigurator.getPort());
    properties.put(Context.SECURITY_AUTHENTICATION, ldapConfigurator.getSecurityAuthentication());
    properties.put(Context.SECURITY_PRINCIPAL, principal);
    properties.put(Context.SECURITY_CREDENTIALS, credentials);

    if (ldapConfigurator.getCustomConnectionParameters() != null) {
      for (String customParameter : ldapConfigurator.getCustomConnectionParameters().keySet()) {
        properties.put(
            customParameter, ldapConfigurator.getCustomConnectionParameters().get(customParameter));
      }
    }

    InitialDirContext context;
    try {
      context = new InitialDirContext(properties);
    } catch (NamingException e) {
      LOGGER.warn("Could not create InitialDirContext for LDAP connection : " + e.getMessage());
      throw new ActivitiException(
          "Could not create InitialDirContext for LDAP connection : " + e.getMessage(), e);
    }
    return context;
  }
Esempio n. 3
0
  private void registerJNDI(DataSourceMetaInfo dsmInfo, Object dsObject)
      throws DataSourceException {
    try {
      PrivilegedCarbonContext.startTenantFlow();
      PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.getTenantId());
      JNDIConfig jndiConfig = dsmInfo.getJndiConfig();
      if (jndiConfig == null) {
        return;
      }
      InitialContext context;
      try {
        context = new InitialContext(jndiConfig.extractHashtableEnv());
      } catch (NamingException e) {
        throw new DataSourceException("Error creating JNDI initial context: " + e.getMessage(), e);
      }
      this.checkAndCreateJNDISubContexts(context, jndiConfig.getName());

      try {
        context.rebind(jndiConfig.getName(), dsObject);
      } catch (NamingException e) {
        throw new DataSourceException(
            "Error in binding to JNDI with name '" + jndiConfig.getName() + "' - " + e.getMessage(),
            e);
      }
    } finally {
      PrivilegedCarbonContext.endTenantFlow();
    }
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions
   *
   * @param q DirectoryQuery
   * @return List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> search(final LDAPDirectoryQuery q) throws LDAPException {
    List<Identity> results = new ArrayList<Identity>();
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }
      SearchControls ctls = new SearchControls();
      List<String> _aux = new ArrayList<String>();
      _aux.add("modifyTimestamp");
      _aux.add("*");
      ctls.setReturningAttributes(_aux.toArray(new String[_aux.size()]));
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = null;
        if (sr.getName().isEmpty()) {
          _e = new LDAPDirectoryEntry(baseDN);
        } else {
          _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
          /*
           * _e = new LDAPEntry(sr.getName() + "," + this.baseDN); if(_e.getID().matches(
           * "^(ldap|ldaps)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9\\-]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\'/\\\\\\+&amp;%\\$#\\=~])*[^\\.\\,\\)\\(\\s]$"
           * )) { URL _url = new URL(_e.getID()); _e.setID(_url.getPath()); }
           */
        }
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        results.add(_e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "search() null pointer");
      throw new LDAPException("search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "search() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return results;
  }
Esempio n. 5
0
  public LDAPInfo lookUp(String username, String password) {
    try {
      String uidFilter = "(" + uidAttr + "=" + username + ")";

      String usersBaseDN = usersDN + "," + baseDN;

      String path = null;

      try {
        path = LDAPUtil.findUserDN(getUrl(), uidFilter, usersBaseDN);
      } catch (NamingException ex) {
        Log.warning(Geonet.LDAP, ex.getMessage());
      }

      if (path == null || path.length() == 0) {
        path = uidAttr + "=" + username + "," + usersDN + "," + baseDN;
      }

      DirContext dc = LDAPUtil.openContext(getUrl(), path, password);

      Map<String, ? extends List<Object>> attr = LDAPUtil.getNodeInfo(dc, path);
      dc.close();

      if (attr == null) {
        Log.warning(Geonet.LDAP, "Username not found :'" + username + "'");
        return null;
      } else {
        LDAPInfo info = new LDAPInfo();

        info.username = username;
        info.password = password;
        info.name = get(attr, nameAttr);
        info.profile = (profileAttr == null) ? defProfile : get(attr, profileAttr);
        if (info.profile.equals("Reviewer")) {
          info.profile = "Hoofdeditor";
        }
        info.email = get(attr, emailAttr);

        info.groups = (groupAttr == null) ? new String[] {defGroup} : getAll(attr, groupAttr);

        if (!profiles.contains(info.profile)) {
          Log.warning(Geonet.LDAP, "Skipping user with unknown profile");
          Log.warning(Geonet.LDAP, "  (C) Username :'******'");
          Log.warning(Geonet.LDAP, "  (C) Profile  :'" + info.profile + "'");
          return null;
        }

        return info;
      }
    } catch (NamingException e) {
      Log.warning(Geonet.LDAP, "Raised exception during LDAP access");
      Log.warning(Geonet.LDAP, "  (C) Message :" + e.getMessage());
      return null;
    }
  }
  /**
   * Search for entry that matches the specific <code>DirectoryQuery</code> conditions. Results will
   * be order using the values of a specific attribute
   *
   * @param q DirectoryQuery
   * @param attribute Name of the attribute that determines the order
   * @return java.util.List<DirectoryEntry>
   * @exception LDAPException
   */
  public List<Identity> sortedSearch(final LDAPDirectoryQuery q, final String attribute)
      throws LDAPException {
    TreeMap<String, Identity> results =
        new TreeMap<String, Identity>(Collator.getInstance(new Locale("es")));
    try {
      LdapContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("Directory service not available");
      }
      SearchControls ctls = new SearchControls();
      if (connection.hasCountLimit()) {
        ctls.setCountLimit(connection.getCountLimit());
      }
      ctls.setSearchScope(connection.getScope());
      ctx.setRequestControls(new Control[] {new SortControl(attribute, Control.NONCRITICAL)});

      String filter = getQueryString(ctx, q);
      NamingEnumeration<SearchResult> answer = ctx.search(baseDN, filter, ctls);
      while (answer.hasMoreElements()) {
        SearchResult sr = answer.nextElement();
        LDAPDirectoryEntry _e = new LDAPDirectoryEntry(sr.getNameInNamespace());
        @SuppressWarnings("unchecked")
        NamingEnumeration<Attribute> ne =
            (NamingEnumeration<Attribute>) sr.getAttributes().getAll();
        while (ne.hasMore()) {
          Attribute att = ne.next();
          Object[] attrs = new Object[att.size()];
          @SuppressWarnings("unchecked")
          NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
          for (int i = 0; nea.hasMore(); i++) {
            attrs[i] = nea.next();
          }
          _e.setAttribute(att.getID(), attrs);
        }
        String _value = String.valueOf(_e.getAttribute(attribute)[0]);
        while (results.containsKey(_value)) {
          _value = _value.concat("0");
        }
        results.put(_value, _e);
      }
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() null pointer");
      throw new LDAPException("sorted search null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } catch (IOException e) {
      _log.log(java.util.logging.Level.ALL, "sortedSearch() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
    return new ArrayList<Identity>(results.values());
  }
Esempio n. 7
0
 /**
  * @return details for specified user, or null if such user doesn't exist
  * @throws SonarException if unable to retrieve details
  */
 public UserDetails doGetUserDetails(Context context) {
   // If there are no userMappings available, we can not retrieve user details.
   String username = context.getUsername();
   LOG.debug("Requesting details for user {}", username);
   if (userMappings.isEmpty()) {
     String errorMessage = "Unable to retrieve user details: No user mappings found.";
     LOG.debug(errorMessage);
     throw new SonarException(errorMessage);
   }
   UserDetails details = null;
   SonarException sonarException = null;
   for (String serverKey : userMappings.keySet()) {
     SearchResult searchResult = null;
     try {
       LdapUserMapping ldapUserMapping = userMappings.get(serverKey);
       searchResult =
           ldapUserMapping
               .createSearch(contextFactories.get(serverKey), username)
               .returns(
                   ldapUserMapping.getEmailAttribute(), ldapUserMapping.getRealNameAttribute())
               .findUnique();
     } catch (NamingException e) {
       // just in case if Sonar silently swallowed exception
       LOG.debug(e.getMessage(), e);
       sonarException =
           new SonarException(
               "Unable to retrieve details for user " + username + " in " + serverKey, e);
     }
     if (searchResult != null) {
       try {
         details = mapUserDetails(serverKey, searchResult);
         // if no exceptions occur, we found the user and mapped his details.
         break;
       } catch (NamingException e) {
         // just in case if Sonar silently swallowed exception
         LOG.debug(e.getMessage(), e);
         sonarException =
             new SonarException(
                 "Unable to retrieve details for user " + username + " in " + serverKey, e);
       }
     } else {
       // user not found
       LOG.debug("User {} not found in " + serverKey, username);
       continue;
     }
   }
   if (details == null && sonarException != null) {
     // No user found and there is an exception so there is a reason the user could not be found.
     throw sonarException;
   }
   return details;
 }
  /**
   * Check if an entry has specific attribute value. This method is more efficient than getting a
   * complete <code>LDAPDirectoryEntry</code> and check the value
   *
   * @param DN Distinguished Name of the entry
   * @param attribute Attribute name
   * @param value Attribute value
   * @return boolean
   * @exception LDAPException
   */
  public boolean checkEntryAttribute(final String DN, final String attribute, final Object value)
      throws LDAPException {
    try {
      DirContext ctx = connection.connect();
      if (ctx == null) {
        throw new LDAPException("directory service not available");
      }

      Object[] _values;
      StringBuilder _sb = new StringBuilder();
      if (value instanceof Object[]) {
        _values = (Object[]) value;
        if (_values.length > 1) {
          _sb.append("(&");
        }
        for (int i = 0; i < _values.length; i++) {
          _sb.append("(");
          _sb.append(attribute);
          _sb.append("={");
          _sb.append(i);
          _sb.append("})");
        }
        if (_values.length > 1) {
          _sb.append(")");
        }
      } else {
        _sb.append("(");
        _sb.append(attribute);
        _sb.append("={0})");
        _values = new Object[] {value};
      }

      SearchControls ctls = new SearchControls();
      ctls.setReturningAttributes(new String[0]);
      ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

      NamingEnumeration<SearchResult> _answer = ctx.search(DN, _sb.toString(), _values, ctls);
      return _answer.hasMoreElements();
    } catch (NullPointerException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntryAttribute() null pointer");
      throw new LDAPException("check entry null pointer");
    } catch (NamingException e) {
      _log.log(java.util.logging.Level.ALL, "checkEntryAttribute() - " + e.getMessage());
      throw new LDAPException(e.getMessage());
    } finally {
      connection.disconnect();
    }
  }
Esempio n. 9
0
  public Hermes getHermesAsMessageFactory() throws HermesException {
    if (!TextUtils.isEmpty(
        HermesBrowser.getBrowser().getConfig().getMessageStoreMessageFactory())) {
      try {
        Hermes hermes =
            (Hermes)
                HermesBrowser.getBrowser()
                    .getContext()
                    .lookup(HermesBrowser.getBrowser().getConfig().getMessageStoreMessageFactory());

        if (hermes != null) {
          return hermes;
        }
      } catch (NamingException ex) {
        log.info(
            "cannot find configured message store message factory, using one from the tree instead: "
                + ex.getMessage(),
            ex);
      }
    }

    if (getLastSelectedHermesTreeNode() == null) {
      return getBrowserModel().getFirstHermesTreeNode().getHermes();
    } else {
      return getLastSelectedHermesTreeNode().getHermes();
    }
  }
  /**
   * Method getParticipant.
   *
   * @param aId - String
   * @return R4EParticipant
   */
  protected R4EParticipant getParticipant(String aId) {
    // First check if the participant already exist in the participant list
    for (R4EParticipant tmpPart : fParticipants) {
      if (aId.equalsIgnoreCase(tmpPart.getId())) {
        return null;
      }
    }
    final R4EParticipant participant = RModelFactory.eINSTANCE.createR4EParticipant();
    if (R4EUIModelController.isUserQueryAvailable()) {
      final IQueryUser query = new QueryUserFactory().getInstance();
      try {
        final List<IUserInfo> users = query.searchByUserId(aId);

        // Fill info with first user returned
        for (IUserInfo user : users) {
          if (user.getUserId().toLowerCase().equals(aId)) {
            participant.setId(user.getUserId().toLowerCase());
            participant.setEmail(user.getEmail());
            fParticipantsDetailsValues.add(UIUtils.buildUserDetailsString(user));
            return participant;
          }
        }
      } catch (NamingException e) {
        R4EUIPlugin.Ftracer.traceError("Exception: " + e.toString() + " (" + e.getMessage() + ")");
        R4EUIPlugin.getDefault().logError("Exception: " + e.toString(), e);
      } catch (IOException e) {
        R4EUIPlugin.getDefault().logWarning("Exception: " + e.toString(), e);
      }
    }
    participant.setId(aId);
    fParticipantsDetailsValues.add("");
    return participant;
  }
Esempio n. 11
0
  public String executar(HttpServletRequest req) throws ExcecaoComando {
    try {
      int idContato = new Integer(req.getParameter("id")).intValue();
      view.BrowserContatos browser =
          (view.BrowserContatos) req.getSession().getAttribute("browserContatos");

      view.FormContato form = new view.FormContato();
      form.setOrigem(browser);
      form.setNome("formContato.jsp");
      form.setContato(model.services.Contatos.recuperar(idContato));
      form.setExclusao(false);
      form.setInclusao(false);
      form.setAlteracao(true);
      form.atualizaCampos();
      form.setTitulo("Alterando contato");
      req.getSession().setAttribute("formContato", form);

      return form.getNome();
    } catch (SQLException ex) {
      Logger.getLogger(AlterarContato.class.getName()).log(Level.SEVERE, null, ex);
      throw new ExcecaoComando(ex.getMessage());
    } catch (NamingException ex) {
      Logger.getLogger(AlterarContato.class.getName()).log(Level.SEVERE, null, ex);
      throw new ExcecaoComando(ex.getMessage());
    }
  }
Esempio n. 12
0
  public LdapContext connect(String userName, String password) {

    // LdapContext ctxLdap = null;
    Hashtable<String, String> envDC = new Hashtable();

    keystore = secres.getString("KEYSTORE");
    System.setProperty("javax.net.ssl.trustStore", keystore);

    log.info("Connecting to ldap using principal=" + userName);

    envDC.put(Context.PROVIDER_URL, host);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, userName); // "*****@*****.**"
    envDC.put(Context.SECURITY_CREDENTIALS, password);
    if (protocol != null && protocol.equalsIgnoreCase("SSL")) {
      envDC.put(Context.SECURITY_PROTOCOL, protocol);
    }

    try {
      return (new InitialLdapContext(envDC, null));
    } catch (NamingException ne) {
      log.info(ne.getMessage());
      return null;
    }
  }
Esempio n. 13
0
  /** Binds mockup <code>IDGeneratorHome</code>'s home. */
  public static void bindIdGenerator() {

    try {
      MockContextFactory.setAsInitial();
      Context context = new InitialContext();

      MockContainer container = new MockContainer(context);

      SessionBeanDescriptor descriptor =
          new SessionBeanDescriptor(
              "IDGeneratorBean/home",
              IDGeneratorHome.class,
              IDGenerator.class,
              new IDGeneratorBean());
      container.deploy(descriptor);
      //            // put object to JNDI
      //            Context ctx = new InitialContext();
      //            unbindIdGenerator();
      //            String path1 = "java:comp";
      //            String path2 = "ejb";
      //            String path3 = "IDGeneratorHome";
      //            ctx = ctx.createSubcontext(path1);
      //            ctx = ctx.createSubcontext(path2);
      //            ctx.bind(path3, new MockRemoteHome());
    } catch (NamingException e) {
      throw new IllegalStateException(
          "Cannot bind 'IDGeneratorHome'. Check the configuration. "
              + "The nested exception is: "
              + e.getMessage(),
          e);
    }
  }
Esempio n. 14
0
  public BranchTO[] getAllBranchByCountry(String countryId) {
    PreparedStatement pstmt = null;
    Connection con = null;
    ResultSet rs = null;
    BranchTO branchTO = null;
    ArrayList<BranchTO> branchList = new ArrayList<BranchTO>();

    try {
      con = DAOFactory.getInstance().getConnection(Connection.TRANSACTION_READ_UNCOMMITTED);
      pstmt = con.prepareStatement(SQLConstants.LIST_BRANCH_BY_COUNTRY_SQL);
      pstmt.setInt(1, Integer.parseInt(countryId));

      rs = pstmt.executeQuery();
      while (rs.next()) {
        branchTO = new BranchTO();
        branchTO.setId(rs.getString("id"));
        branchTO.setCode(Utility.trim(rs.getString("code")));
        branchTO.setName(Utility.trim(rs.getString("name")));
        branchTO.setStatus(Utility.trim(rs.getString("status")));
        branchList.add(branchTO);
      }

      return (BranchTO[]) branchList.toArray(new BranchTO[0]);

    } catch (SQLException e) {
      throw new DataException(e.getMessage());
    } catch (NamingException e) {
      throw new DataException(e.getMessage());
    } finally {
      Utility.closeAll(null, pstmt, con);
    }
  }
  private DataView<LdapUser> newGroupMembersListView(LdapGroup group) {
    List<LdapUser> users;
    try {
      users = group.getMembers();
    } catch (NamingException e) {
      logger.warn(e.getMessage(), e);
      users = new ArrayList<>(0);
    }
    DataView<LdapUser> members =
        new DataView<LdapUser>("membersList", new LdapGroupUsersProvider(users)) {

          @Override
          protected void populateItem(Item<LdapUser> item) {
            LdapUser user = item.getModelObject();
            WebMarkupContainer container = new WebMarkupContainer("member");
            ExternalLink mail =
                new ExternalLink(
                    "mail", Model.of("mailto:" + user.getMail()), new PropertyModel(user, "mail"));
            Label userName = new Label("username", new PropertyModel(user, "userName"));
            final String fullName = user.getFullName();
            Label fullNameLabel = new Label("fullname", Model.of(fullName));
            fullNameLabel.setVisible(fullName != null);
            container.add(mail);
            container.add(userName);
            container.add(fullNameLabel);
            item.add(container);
          }
        };
    members.setOutputMarkupId(true);
    return members;
  }
  /**
   * 获取名称为dataSourceName的 DataSource.
   *
   * @param dataSourceName
   * @return
   * @throws SQLException
   */
  public DataSource getDataSource(String dataSourceName) throws SQLException {

    // 是否是已经获取的DataSource对象。
    DataSource ods = dataSourceMap.get(dataSourceName);
    if (ods != null) {
      return ods;
    }

    DataSource ds = null;
    //		1.从上下文根据JNDI获取DataSource
    Context initCtx = null;
    try {
      initCtx = new InitialContext(); // 创建上下文实例

      //			get DataSource by different Servlet Container Type.
      // Tomcat5 需要做特殊的处理
      Context envCtx = (Context) initCtx.lookup("java:comp/env");

      ds = (DataSource) envCtx.lookup(dataSourceName);
      dataSourceMap.put(dataSourceName, ds); // 缓存起来
      return ds;

    } catch (NamingException ex) {
      log.fatal("cant get the new InitialContext()");
      log.debug("debug", ex);
      /// ex.pri ntStackTrace();
      throw new SQLException(ex.getMessage());

    } catch (Exception ex) {
      log.fatal("cant get the new InitialContext()");
      log.debug("debug", ex);
      /// ex.pri ntStackTrace();
      throw new SQLException(ex.getMessage());
    }
  }
Esempio n. 17
0
  public boolean updateBranch(BranchTO branchTO) {
    PreparedStatement pstmt = null;
    Connection con = null;
    int result;

    try {
      con = DAOFactory.getInstance().getConnection(Connection.TRANSACTION_READ_UNCOMMITTED);
      pstmt = con.prepareStatement(SQLConstants.UPDATE_BRANCH_SQL);
      pstmt.setString(1, Utility.trim(branchTO.getName()));
      pstmt.setString(2, Utility.trim(branchTO.getCountry().getId()));
      pstmt.setString(3, Utility.trim(branchTO.getStatus()));
      pstmt.setInt(4, 1);
      pstmt.setString(5, Utility.trim(branchTO.getId()));

      result = pstmt.executeUpdate();
      if (result > 0) {
        return true;
      } else {
        return false;
      }
    } catch (SQLException e) {
      throw new DataException(e.getMessage());
    } catch (NamingException e) {
      throw new DataException(e.getMessage());
    } finally {
      Utility.closeAll(null, pstmt, con);
    }
  }
Esempio n. 18
0
 public boolean agregar() {
   boolean ok = false;
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso:", "agregar: mbUpc");
   //        RequestContext context = RequestContext.getCurrentInstance();
   try {
     if (this.upc.getUpc().equals("")) {
       fMsg.setSeverity(FacesMessage.SEVERITY_WARN);
       fMsg.setDetail("Se requiere un UPC !");
     } else {
       this.dao = new DAOUpcs();
       this.dao.agregar(this.upc);
       this.cargaListaUpcs();
       ok = true;
     }
   } catch (NamingException ex) {
     fMsg.setDetail(ex.getMessage());
   } catch (SQLException ex) {
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
   //        context.addCallbackParam("okUpc", ok);
   return ok;
 }
Esempio n. 19
0
 /**
  * Creates the initial JNDI context to work with.
  *
  * @return context {@link InitialContext}
  * @throws ProcessingException
  */
 public InitialContext createInitialContext() throws ProcessingException {
   Hashtable<String, String> props = new Hashtable<String, String>();
   if (m_initialContextFactory != null) {
     props.put(Context.INITIAL_CONTEXT_FACTORY, m_initialContextFactory);
   }
   if (m_providerUrl != null) {
     props.put(Context.PROVIDER_URL, m_providerUrl);
   }
   if (m_userName != null && m_userName.length() > 0) {
     props.put(Context.SECURITY_PRINCIPAL, m_userName);
   }
   if (m_password != null) {
     props.put(Context.SECURITY_CREDENTIALS, m_password);
   }
   InitialContext ctx;
   try {
     if (props.size() > 0) {
       ctx = new InitialContext(props);
     } else {
       ctx = new InitialContext();
     }
   } catch (NamingException e) {
     throw new ProcessingException(e.getMessage(), e.getCause());
   }
   return ctx;
 }
Esempio n. 20
0
 public void grabar() {
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
   if (this.zona == null || this.zona.getIdZona() == 0) {
     fMsg.setDetail("Seleccione una zona !!");
   } else if (this.grupo == null || this.grupo.getIdGrupo() == 0) {
     fMsg.setDetail("Seleccione un grupo !!");
   } else if (this.detalle == null || this.detalle.getImpuesto().getIdImpuesto() == 0) {
     fMsg.setDetail("Seleccione un impuesto de la lista !!");
   } else {
     try {
       this.dao = new DAOImpuestosDetalle();
       this.detalles =
           this.dao.grabar(zona.getIdZona(), grupo.getIdGrupo(), this.detalle, this.periodo);
       fMsg.setSeverity(FacesMessage.SEVERITY_INFO);
       fMsg.setDetail("La operación se realizó con éxito !!");
     } catch (SQLException ex) {
       fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
       fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
     } catch (NamingException ex) {
       fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
       fMsg.setDetail(ex.getMessage());
     }
   }
   FacesContext.getCurrentInstance().addMessage(null, fMsg);
 }
Esempio n. 21
0
  public void eliminarPeriodo() {
    FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
    if (this.zona == null || this.zona.getIdZona() == 0) {
      fMsg.setDetail("Seleccione una zona !!");
    } else if (this.grupo == null || this.grupo.getIdGrupo() == 0) {
      fMsg.setDetail("Seleccione un grupo !!");
    } else if (this.periodo.equals("1")) {
      fMsg.setDetail("No se puede eliminar el período actual !!");
    } else {
      try {
        this.dao = new DAOImpuestosDetalle();
        this.dao.eliminarPeriodo(this.zona.getIdZona(), this.grupo.getIdGrupo());
        this.detalles = new ArrayList<ImpuestoDetalle>();
        this.detalle = null;

        fMsg.setSeverity(FacesMessage.SEVERITY_INFO);
        fMsg.setDetail("La operación se realizó con éxito !!");
      } catch (SQLException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
      } catch (NamingException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getMessage());
      }
    }
    FacesContext.getCurrentInstance().addMessage(null, fMsg);
  }
Esempio n. 22
0
 public void cargarDetalles(int idZona, int idGrupo) {
   boolean ok = false;
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
   if (this.periodo == null) {
     this.periodo = "1";
   }
   try {
     if (idZona == 0 || idGrupo == 0) {
       this.detalles = new ArrayList<ImpuestoDetalle>();
     } else {
       this.dao = new DAOImpuestosDetalle();
       this.detalles = this.dao.obtenerDetalles(idZona, idGrupo, this.periodo);
     }
     ok = true;
   } catch (SQLException ex) {
     fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   } catch (NamingException ex) {
     fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
     fMsg.setDetail(ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
 }
Esempio n. 23
0
  public void crearPeriodo() {
    FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Aviso:", "");
    if (this.zona == null || this.zona.getIdZona() == 0) {
      fMsg.setDetail("Seleccione una zona !!");
    } else if (this.grupo == null || this.grupo.getIdGrupo() == 0) {
      fMsg.setDetail("Seleccione un grupo !!");
    } else if (this.periodo.equals("1")) {
      fMsg.setDetail("No se puede crear un período actual, debe ser uno siguiente !!");
    } else if (this.detalles.isEmpty()) {
      try {
        Date fechaInicial = Utilerias.addDays(fechaTope, 1);

        this.dao = new DAOImpuestosDetalle();
        this.detalles =
            this.dao.crearPeriodo(
                this.zona.getIdZona(),
                this.grupo.getIdGrupo(),
                this.periodo,
                new java.sql.Date(fechaInicial.getTime()));
        this.detalle = null;

        fMsg.setSeverity(FacesMessage.SEVERITY_INFO);
        fMsg.setDetail("La operación se realizó con éxito !!");
      } catch (SQLException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
      } catch (NamingException ex) {
        fMsg.setSeverity(FacesMessage.SEVERITY_ERROR);
        fMsg.setDetail(ex.getMessage());
      }
    } else {
      fMsg.setDetail("Ya existe un período siguiente, modifique o elimine y velva a crear !!");
    }
    FacesContext.getCurrentInstance().addMessage(null, fMsg);
  }
Esempio n. 24
0
 public static int verifyMaliciousPassword(String login, String mail) {
   String mailAdresse = "";
   Ldap adminConnection = new Ldap();
   adminConnection.SetEnv(
       Play.configuration.getProperty("ldap.host"),
       Play.configuration.getProperty("ldap.admin.dn"),
       Play.configuration.getProperty("ldap.admin.password"));
   Attributes f = adminConnection.getUserInfo(adminConnection.getLdapEnv(), login);
   try {
     NamingEnumeration e = f.getAll();
     while (e.hasMore()) {
       javax.naming.directory.Attribute a = (javax.naming.directory.Attribute) e.next();
       String attributeName = a.getID();
       String attributeValue = "";
       Enumeration values = a.getAll();
       while (values.hasMoreElements()) {
         attributeValue = values.nextElement().toString();
       }
       if (attributeName.equals("mail")) {
         mailAdresse = attributeValue;
       }
     }
   } catch (javax.naming.NamingException e) {
     System.out.println(e.getMessage());
     return 0;
   } finally {
     if (mailAdresse.equals("")) {
       return Invitation.USER_NOTEXIST;
     } else if (mailAdresse.equals(mail)) {
       return Invitation.ADDRESSES_MATCHE;
     } else {
       return Invitation.ADDRESSES_NOTMATCHE;
     }
   }
 }
Esempio n. 25
0
  public Map<String, String> getAttributes(User user) throws DataSourceException, ConfigException {
    try {
      String s =
          "(&(objectClass="
              + source.getUsersObjectClassValue()
              + ")("
              + source.getUsersIdKey()
              + "="
              + user.getUid()
              + "))";
      List<SearchResult> r = this.search(s, SecurityEntityType.USER);
      if (!r.isEmpty()) {
        Attributes attrs = r.get(0).getAttributes();
        Map<String, String> items = new HashMap<String, String>();
        NamingEnumeration<? extends Attribute> lst = attrs.getAll();
        while (lst.hasMoreElements()) {
          Attribute attr = lst.nextElement();
          if (attr.get() != null) {
            items.put(attr.getID(), attr.get().toString());
          }
        }

        return items;
      } else {
        return null;
      }
    } catch (javax.naming.AuthenticationException e) {
      throw new ConfigException(e, "LDAP connection failed, please check your settings");
    } catch (NamingException e) {
      throw new DataSourceException(e, "LDAP Exception : " + e.getMessage());
    }
  }
Esempio n. 26
0
 public boolean eliminar() {
   boolean ok = false;
   RequestContext context = RequestContext.getCurrentInstance();
   FacesMessage fMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Aviso:", "eliminar: mbUpc");
   try {
     if (this.listaUpcs.size() > 2 && this.upc.isActual()) {
       fMsg.setSeverity(FacesMessage.SEVERITY_WARN);
       fMsg.setDetail("No se puede eliminar, cambie primero de actual");
     } else {
       this.dao = new DAOUpcs();
       this.dao.Eliminar(this.upc.getUpc());
       this.cargaListaUpcs();
       ok = true;
     }
   } catch (NamingException ex) {
     fMsg.setDetail(ex.getMessage());
   } catch (SQLException ex) {
     fMsg.setDetail(ex.getErrorCode() + " " + ex.getMessage());
   }
   if (!ok) {
     FacesContext.getCurrentInstance().addMessage(null, fMsg);
   }
   context.addCallbackParam("okUpc", ok);
   return ok;
 }
 /**
  * Gets an <code>LDAPDirectoryEntry</code> object that represent an entry on directory. You can
  * provide a list of attributes to be ignored when load the entry data. Look for attribute matches
  * using a map of values
  *
  * @param DN Distinguished Name of the entry
  * @param ignore_attributes You can indicate here a list of attribute to be ignored when load all
  *     entry data. this is useful if you have some big data in some attributes and do you want to
  *     ignore that
  * @param attribute_matches Map with attribute names and values to match
  * @return LDAPDirectoryEntry
  * @exception LDAPException
  */
 public LDAPDirectoryEntry getEntry(
     final String DN,
     final List<String> ignore_attributes,
     final Map<String, String> attribute_matches)
     throws LDAPException {
   LDAPDirectoryEntry _e = null;
   try {
     _e = new LDAPDirectoryEntry(DN);
     DirContext ctx = connection.connect();
     if (ctx == null) {
       throw new LDAPException("directory service not available");
     }
     Attributes atts = ctx.getAttributes(DN);
     if (atts == null) {
       return null;
     }
     @SuppressWarnings("unchecked")
     NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) atts.getAll();
     while (ne.hasMore()) {
       Attribute att = ne.next();
       if (ignore_attributes == null || !ignore_attributes.contains(att.getID())) {
         List<Object> _values = new ArrayList<Object>();
         @SuppressWarnings("unchecked")
         NamingEnumeration<Object> nea = (NamingEnumeration<Object>) att.getAll();
         while (nea.hasMore()) {
           Object _value = nea.next();
           if (attribute_matches == null || !attribute_matches.containsKey(att.getID())) {
             _values.add(_value);
           } else if (attribute_matches.get(att.getID()) != null
               && String.valueOf(_value).contains(attribute_matches.get(att.getID()))) {
             _values.add(_value);
           }
         }
         _e.setAttribute(att.getID(), _values.toArray());
       }
     }
   } catch (NullPointerException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() null pointer");
     throw new LDAPException("get entry null pointer");
   } catch (NamingException e) {
     _log.log(java.util.logging.Level.ALL, "getEntry() - " + e.getMessage());
     throw new LDAPException(e.getMessage());
   } finally {
     connection.disconnect();
   }
   return _e;
 }
 private StudentBPOLocal getStudentBPOLocal() {
   try {
     return StudentBPOUtil.getLocal();
   } catch (NamingException e) {
     System.out.print("Error :" + e.getMessage());
     return null;
   }
 }
Esempio n. 29
0
  /**
   * Returns a list of AD Groups using the service account
   *
   * @return list of AD Groups
   */
  public static List<String> getADGroupsByServiceAccount() {

    String username = MessageUtils.getMessage("ldap.service.account.username");
    String password = MessageUtils.getMessage("ldap.service.account.password");
    List<String> awsAllGroups = null;

    logger.debug("Starting.....");
    if (username == null || password == null) {
      return new ArrayList<String>();
    }
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, MessageUtils.getMessage("ldap.service.account.url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    DirContext ctx = null;

    try {
      logger.debug("Getting AWS groups using service account");
      ctx = new InitialDirContext(env);
      logger.debug("After InitialDirContext");
      SearchControls controls = new SearchControls();
      controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      String attr[] = {"samaccountname"};
      controls.setReturningAttributes(attr);
      NamingEnumeration<SearchResult> result =
          ctx.search(
              MessageUtils.getMessage("ldap.service.account.conf.name"),
              MessageUtils.getMessage("ldap.service.account.conf.filter"),
              controls);
      awsAllGroups = new ArrayList<String>();

      SearchResult sr = null;
      // Loop through the search results
      while (result.hasMoreElements()) {
        sr = (SearchResult) result.next();
        awsAllGroups.add(sr.getName().substring(3));
      }

      return awsAllGroups;
    } catch (AuthenticationException e) {
      logger.error("Service account details are not correct." + e.getMessage());
      return null;
    } catch (NamingException e) {
      logger.error("Unable to connect" + e.getMessage());
      return new ArrayList<String>();
    } finally {
      if (ctx != null) {
        try {
          ctx.close();
        } catch (NamingException e) {

        }
      }
    }
  }
  @Override
  public User getUser(Renderer renderer, String username, String password) throws IOException {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
      throw new AuthException("Username or password is empty");
    if (StringUtils.isEmpty(renderer.getAuthServer()))
      throw new AuthException("No auth server given, check the parameters of the renderer");

    ActiveDirectory activeDirectory = null;
    try {
      String domain = renderer.getAuthDomain();
      String authServer = renderer.getAuthServer();

      User user = AuthUserCache.INSTANCE.get(username, domain);
      if (user != null) return user;

      NtlmPasswordAuthentication ntlmAuth = getNtlmAuth(renderer, username, password);
      UniAddress dc = UniAddress.getByName(authServer, true);
      SmbSession.logon(dc, ntlmAuth);

      activeDirectory =
          new ActiveDirectory(authServer, ntlmAuth.getUsername(), ntlmAuth.getPassword(), domain);

      NamingEnumeration<SearchResult> result = activeDirectory.findUser(username);
      Attributes attrs = ActiveDirectory.getAttributes(result);
      if (attrs == null) throw new AuthException("No user found: " + username);

      String userId = ActiveDirectory.getObjectSID(attrs);
      List<ADGroup> groups = new ArrayList<ADGroup>();
      activeDirectory.findUserGroups(attrs, groups);
      String dnUser = ActiveDirectory.getStringAttribute(attrs, "DistinguishedName");
      if (!StringUtils.isEmpty(dnUser)) activeDirectory.findUserGroup(dnUser, groups);

      Logging.info("USER authenticated: " + user);

      user =
          new User(
              userId.toLowerCase(),
              username.toLowerCase(),
              password,
              ActiveDirectory.toArray(groups, "everyone"),
              ActiveDirectory.getDisplayString(domain, username));
      AuthUserCache.INSTANCE.add(username, domain, user);
      return user;

    } catch (SmbAuthException e) {
      Logging.warn(e);
      throw new AuthException("Authentication error (SmbAuthException) : " + e.getMessage());
    } catch (UnknownHostException e) {
      Logging.warn(e);
      throw new AuthException("Authentication error (UnknownHostException) : " + e.getMessage());
    } catch (NamingException e) {
      Logging.warn(e);
      throw new AuthException("LDAP error (NamingException) : " + e.getMessage());
    } finally {
      IOUtils.close(activeDirectory);
    }
  }