Example usage for javax.naming NamingException getMessage

List of usage examples for javax.naming NamingException getMessage

Introduction

In this page you can find the example usage for javax.naming NamingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
public boolean authenticate(String username, String password) throws DirectoryException {

    if (password == null || "".equals(password.trim())) {
        // never use anonymous bind as a way to authenticate a user in
        // Nuxeo EP
        return false;
    }//from  w w w  .  j  a va  2  s  . co  m

    // lookup the user: fetch its dn
    SearchResult entry;
    try {
        entry = getLdapEntry(username);
    } catch (NamingException e) {
        throw new DirectoryException("failed to fetch the ldap entry for " + username, e);
    }
    if (entry == null) {
        // no such user => authentication failed
        return false;
    }
    String dn = entry.getNameInNamespace();
    Properties env = (Properties) getDirectory().getContextProperties().clone();
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);

    InitialLdapContext authenticationDirContext = null;
    try {
        // creating a context does a bind
        log.debug(String.format("LDAP bind dn='%s'", dn));
        // noinspection ResultOfObjectAllocationIgnored
        authenticationDirContext = new InitialLdapContext(env, null);
        // force reconnection to prevent from using a previous connection
        // with an obsolete password (after an user has changed his
        // password)
        authenticationDirContext.reconnect(null);
        log.debug("Bind succeeded, authentication ok");
        return true;
    } catch (NamingException e) {
        log.debug("Bind failed: " + e.getMessage());
        // authentication failed
        return false;
    } finally {
        try {
            if (authenticationDirContext != null) {
                authenticationDirContext.close();
            }
        } catch (NamingException e) {
            log.error("Error closing authentication context when biding dn " + dn, e);
            return false;
        }
    }
}

From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java

/**
 * Initialize the servlet./*  ww  w.  j  av a  2 s  .c om*/
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        PdsConf pdsConf = (PdsConf) envContext.lookup("bean/PdsConf");
        conf = pdsConf.getConf();
        memcache = (CacheController) envContext.lookup("bean/CacheController");
        ds = (DataSource) envContext.lookup("jdbc/DrsDB");
    } catch (NamingException e) {
        e.printStackTrace();
    }

    cache = conf.getString("cache");
    idsUrl = conf.getString("ids");
    ftsUrl = conf.getString("fts");
    giffy = conf.getString("t2gif");
    cacheUrl = conf.getString("cacheUrl");
    pdsUrl = conf.getString("pds");
    nrsUrl = conf.getString("nrsUrl");
    String logFile = conf.getString("logFile");

    maxThumbnails = conf.getString("maxThumbnails");

    //Configure the logger
    logger = Logger.getLogger("edu.harvard.hul.ois.pds.ws");
    try {
        XmlLayout myLayout = new XmlLayout();
        //an appender for the access log
        Appender myAppender = new DailyRollingFileAppender(myLayout, logFile, conf.getString("logRollover"));
        logger.addAppender(myAppender);
    } catch (Exception e) {
        WebAppLogMessage message = new WebAppLogMessage();
        message.setContext("init logger");
        message.setMessage("Error initializing logger");
        logger.error(message, e);
        throw new ServletException(e.getMessage());
    }
    //reset the logger for this class
    logger = Logger.getLogger(PDSWebService.class);

    System.setProperty("org.xml.sax.driver", "org.apache.xerces.parsers.SAXParser");

    //init pdf conversions hash
    pdfConversions = new Hashtable<String, ArrayList<Integer>>();

    //Log successful servlet init
    WebAppLogMessage message = new WebAppLogMessage();
    message.setMessage("Servlet init()");
    logger.info(message);

    drs2Service = new ServiceWrapper(conf.getString("drs2ServiceURL"), conf.getString("drs2AppKey"), 1);

}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;/* w  ww. j  ava  2  s  .  c  om*/
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Delete value: ***");
                    } else {
                        log.debug("Delete value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:it.doqui.index.ecmengine.business.publishing.EcmEnginePublisherBean.java

/**
 * Metodo chiamato dall'invocazione del metodo {@code create()} sulla
 * Home Interface dell'EJB di pubblicazione dei servizi. Esso si occupa del reperimento
 * degli EJB wrapper dei servizi applicativi, dell'inizializzazione del logger e dello
 * stopwatch.//from w w  w  . ja v a 2  s .  co m
 *
 * @throws EJBException Se si verificano errori durante l'inizializzazione dell'EJB.
 * @throws RemoteException Se si verificano errori durante la comunicazione remota.
 */
public void ejbCreate() throws EJBException, RemoteException {
    logger = LogFactory.getLog(ECMENGINE_BUSINESS_LOG_CATEGORY);
    logger.debug("[EcmEnginePublisherBean::ejbCreate] BEGIN");

    try {
        this.initialContext = new InitialContext();

        logger.debug("[EcmEnginePublisherBean::ejbCreate] Lookup dei servizi applicativi.");
        this.authenticationServiceHome = (AuthenticationSvcHome) lookup(
                FoundationBeansConstants.AUTHENTICATION_SERVICE_NAME_LOCAL);
        this.authorityServiceHome = (AuthoritySvcHome) lookup(
                FoundationBeansConstants.AUTHORITY_SERVICE_NAME_LOCAL);
        this.contentServiceHome = (ContentSvcHome) lookup(FoundationBeansConstants.CONTENT_SERVICE_NAME_LOCAL);
        this.dictionaryServiceHome = (DictionarySvcHome) lookup(
                FoundationBeansConstants.DICTIONARY_SERVICE_NAME_LOCAL);
        this.fileFolderServiceHome = (FileFolderSvcHome) lookup(
                FoundationBeansConstants.FILEFOLDER_SERVICE_NAME_LOCAL);
        this.namespaceServiceHome = (NamespaceSvcHome) lookup(
                FoundationBeansConstants.NAMESPACE_SERVICE_NAME_LOCAL);
        this.nodeServiceHome = (NodeSvcHome) lookup(FoundationBeansConstants.NODE_SERVICE_NAME_LOCAL);
        this.nodeArchiveServiceHome = (NodeArchiveSvcHome) lookup(
                FoundationBeansConstants.NODE_ARCHIVE_SERVICE_NAME_LOCAL);
        this.ownableServiceHome = (OwnableSvcHome) lookup(FoundationBeansConstants.OWNABLE_SERVICE_NAME_LOCAL);
        this.permissionServiceHome = (PermissionSvcHome) lookup(
                FoundationBeansConstants.PERMISSION_SERVICE_NAME_LOCAL);
        this.personServiceHome = (PersonSvcHome) lookup(FoundationBeansConstants.PERSON_SERVICE_NAME_LOCAL);
        this.searchServiceHome = (SearchSvcHome) lookup(FoundationBeansConstants.SEARCH_SERVICE_NAME_LOCAL);
        this.transactionServiceHome = (TransactionSvcHome) lookup(
                FoundationBeansConstants.TRANSACTION_SERVICE_NAME_LOCAL);
        this.lockServiceHome = (LockSvcHome) lookup(FoundationBeansConstants.LOCK_SERVICE_NAME_LOCAL);
        this.checkOutCheckInHome = (CheckOutCheckInSvcHome) lookup(
                FoundationBeansConstants.CHECKOUT_CHECKIN_NAME_LOCAL);
        this.copyHome = (CopySvcHome) lookup(FoundationBeansConstants.COPY_NAME_LOCAL);
        this.versionHome = (VersionSvcHome) lookup(FoundationBeansConstants.VERSION_NAME_LOCAL);
        this.actionHome = (ActionSvcHome) lookup(FoundationBeansConstants.ACTION_SERVICE_NAME_LOCAL);
        this.ruleHome = (RuleSvcHome) lookup(FoundationBeansConstants.RULE_SERVICE_NAME_LOCAL);
        this.tenantAdminHome = (TenantAdminSvcHome) lookup(
                FoundationBeansConstants.TENANT_ADMIN_SERVICE_NAME_LOCAL);
        this.repoAdminHome = (RepoAdminSvcHome) lookup(FoundationBeansConstants.REPO_ADMIN_SERVICE_NAME_LOCAL);
        this.jobHome = (JobSvcHome) lookup(FoundationBeansConstants.JOB_SERVICE_NAME_LOCAL);
        this.auditHome = (AuditSvcHome) lookup(FoundationBeansConstants.AUDIT_SERVICE_NAME_LOCAL);
        this.auditTrailHome = (AuditTrailSvcHome) lookup(
                FoundationBeansConstants.AUDIT_TRAIL_SERVICE_NAME_LOCAL);
        this.mimetypeHome = (MimetypeSvcHome) lookup(FoundationBeansConstants.MIMETYPE_SERVICE_NAME_LOCAL);
        this.integrityHome = (IntegritySvcHome) lookup(FoundationBeansConstants.INTEGRITY_SERVICE_NAME_LOCAL);
        this.fileFormatHome = (FileFormatSvcHome) lookup(
                FoundationBeansConstants.FILE_FORMAT_SERVICE_NAME_LOCAL);
        this.categoryHome = (CategorySvcHome) lookup(FoundationBeansConstants.CATEGORY_SERVICE_NAME_LOCAL);
        this.exporterHome = (ExportSvcHome) lookup(FoundationBeansConstants.EXPORTER_SERVICE_NAME_LOCAL);
        this.importerHome = (ImportSvcHome) lookup(FoundationBeansConstants.IMPORTER_SERVICE_NAME_LOCAL);

        logger.debug("[EcmEnginePublisherBean::ejbCreate] Creazione dei servizi applicativi.");
        this.authenticationService = this.authenticationServiceHome.create();
        this.authorityService = this.authorityServiceHome.create();
        this.contentService = this.contentServiceHome.create();
        this.dictionaryService = this.dictionaryServiceHome.create();
        this.nodeService = this.nodeServiceHome.create();
        this.nodeArchiveService = this.nodeArchiveServiceHome.create();
        this.ownableService = this.ownableServiceHome.create();
        this.permissionService = this.permissionServiceHome.create();
        this.personService = this.personServiceHome.create();
        this.searchService = this.searchServiceHome.create();
        this.transactionService = this.transactionServiceHome.create();
        this.lockService = this.lockServiceHome.create();
        this.checkOutCheckInService = this.checkOutCheckInHome.create();
        this.copyService = this.copyHome.create();
        this.versionService = this.versionHome.create();
        this.actionService = this.actionHome.create();
        this.ruleService = this.ruleHome.create();
        this.tenantAdminService = this.tenantAdminHome.create();
        this.repoAdminService = this.repoAdminHome.create();
        this.jobService = this.jobHome.create();
        this.auditService = this.auditHome.create();
        this.auditTrailService = this.auditTrailHome.create();
        this.mimetypeService = this.mimetypeHome.create();
        this.integrityService = this.integrityHome.create();
        this.namespaceService = this.namespaceServiceHome.create();
        this.fileFolderService = this.fileFolderServiceHome.create();
        this.fileFormatService = this.fileFormatHome.create();
        this.categoryService = this.categoryHome.create();
        this.exporterService = this.exporterHome.create();
        this.importerService = this.importerHome.create();

    } catch (NamingException e) {
        logger.error("[EcmEnginePublisherBean::ejbCreate] Errore nel lookup dei bean dei "
                + "servizi applicativi: " + e.getMessage());
        throw new EJBException("Errore nel lookup dei bean dei servizi applicativi.");
    } catch (CreateException e) {
        logger.error("[EcmEnginePublisherBean::ejbCreate] Errore nella creazione dei bean dei"
                + "servizi applicativi: " + e.getMessage());
        throw new EJBException("Errore nella creazione dei bean dei servizi applicativi.");
    } finally {
        logger.debug("[EcmEnginePublisherBean::ejbCreate] END");
    }
}

From source file:com.espertech.esper.core.EPStatementStartMethod.java

private EPStatementStartResult startCreateWindow(boolean isNewStatement, boolean isRecoveringStatement)
        throws ExprValidationException, ViewProcessingException {
    final FilterStreamSpecCompiled filterStreamSpec = (FilterStreamSpecCompiled) statementSpec.getStreamSpecs()
            .get(0);/*from w ww . j  a v a  2  s  . c  om*/
    String windowName = statementSpec.getCreateWindowDesc().getWindowName();
    EventType windowType = filterStreamSpec.getFilterSpec().getFilterForEventType();

    // Create streams and views
    Viewable eventStreamParentViewable;
    ViewFactoryChain unmaterializedViewChain;

    // Create view factories and parent view based on a filter specification
    // Since only for non-joins we get the existing stream's lock and try to reuse it's views
    boolean filterSubselectSameStream = determineSubquerySameStream(filterStreamSpec);
    Pair<EventStream, StatementLock> streamLockPair = services.getStreamService().createStream(
            statementContext.getStatementId(), filterStreamSpec.getFilterSpec(),
            statementContext.getFilterService(), statementContext.getEpStatementHandle(), false, false,
            statementContext, true, filterSubselectSameStream, statementContext.getAnnotations());
    eventStreamParentViewable = streamLockPair.getFirst();

    // Use the re-used stream's lock for all this statement's locking needs
    if (streamLockPair.getSecond() != null) {
        statementContext.getEpStatementHandle().setStatementLock(streamLockPair.getSecond());
    }

    // Create data window view factories
    unmaterializedViewChain = services.getViewService().createFactories(0,
            eventStreamParentViewable.getEventType(), filterStreamSpec.getViewSpecs(),
            filterStreamSpec.getOptions(), statementContext);

    ValueAddEventProcessor optionalRevisionProcessor = statementContext.getValueAddEventService()
            .getValueAddProcessor(windowName);
    boolean isPrioritized = services.getEngineSettingsService().getEngineSettings().getExecution()
            .isPrioritized();
    boolean isEnableSubqueryIndexShare = HintEnum.ENABLE_WINDOW_SUBQUERY_INDEXSHARE
            .getHint(statementSpec.getAnnotations()) != null;
    if (!isEnableSubqueryIndexShare
            && unmaterializedViewChain.getViewFactoryChain().get(0) instanceof VirtualDWViewFactory) {
        isEnableSubqueryIndexShare = true; // index share is always enabled for virtual data window (otherwise it wouldn't make sense)
    }
    services.getNamedWindowService().addProcessor(windowName, windowType,
            statementContext.getEpStatementHandle(), statementContext.getStatementResultService(),
            optionalRevisionProcessor, statementContext.getExpression(), statementContext.getStatementName(),
            isPrioritized, statementContext, isEnableSubqueryIndexShare);

    // The root view of the named window
    NamedWindowProcessor processor = services.getNamedWindowService()
            .getProcessor(statementSpec.getCreateWindowDesc().getWindowName());
    View rootView = processor.getRootView();
    eventStreamParentViewable.addView(rootView);

    // request remove stream capability from views
    ViewResourceDelegate viewResourceDelegate = new ViewResourceDelegateImpl(
            new ViewFactoryChain[] { unmaterializedViewChain }, statementContext);
    if (!viewResourceDelegate.requestCapability(0, new RemoveStreamViewCapability(false), null)) {
        throw new ExprValidationException(NamedWindowService.ERROR_MSG_DATAWINDOWS);
    }

    // Materialize views
    Viewable finalView = services.getViewService().createViews(rootView,
            unmaterializedViewChain.getViewFactoryChain(), statementContext);

    // If this is a virtual data window implementation, bind it to the context for easy lookup
    StopCallback envStopCallback = null;
    if (finalView instanceof VirtualDWView) {
        final String objectName = "/virtualdw/" + windowName;
        final VirtualDWView virtualDWView = (VirtualDWView) finalView;
        try {
            services.getEngineEnvContext().bind(objectName, virtualDWView.getVirtualDataWindow());
        } catch (NamingException e) {
            throw new ViewProcessingException("Invalid name for adding to context:" + e.getMessage(), e);
        }
        envStopCallback = new StopCallback() {
            public void stop() {
                try {
                    virtualDWView.destroy();
                    services.getEngineEnvContext().unbind(objectName);
                } catch (NamingException e) {
                }
            }
        };
    }
    final StopCallback environmentStopCallback = envStopCallback;

    // create stop method using statement stream specs
    EPStatementStopMethod stopMethod = new EPStatementStopMethod() {
        public void stop() {
            statementContext.getStatementStopService().fireStatementStopped();
            boolean filterSubselectSameStream = determineSubquerySameStream(filterStreamSpec);
            services.getStreamService().dropStream(filterStreamSpec.getFilterSpec(),
                    statementContext.getFilterService(), false, false, true, filterSubselectSameStream);
            String windowName = statementSpec.getCreateWindowDesc().getWindowName();
            try {
                NamedWindowProcessor processor = services.getNamedWindowService().getProcessor(windowName);
                if (processor.isVirtualDataWindow()) {
                    processor.getVirtualDataWindow().handleStopWindow();
                }
            } catch (ExprValidationException e) {
                log.warn("Named window processor by name '" + windowName + "' has not been found");
            }
            services.getNamedWindowService().removeProcessor(windowName);
            if (environmentStopCallback != null) {
                environmentStopCallback.stop();
            }
        }
    };

    // Attach tail view
    boolean isBatchView = finalView instanceof BatchingDataWindowView;
    NamedWindowTailView tailView = processor.getTailView();
    tailView.setBatchView(isBatchView);
    processor.getRootView().setBatchView(isBatchView);
    finalView.addView(tailView);
    finalView = tailView;

    // Add a wildcard to the select clause as subscribers received the window contents
    statementSpec.getSelectClauseSpec().getSelectExprList().clear();
    statementSpec.getSelectClauseSpec().add(new SelectClauseElementWildcard());
    statementSpec.setSelectStreamDirEnum(SelectClauseStreamSelectorEnum.RSTREAM_ISTREAM_BOTH);

    StreamTypeService typeService = new StreamTypeServiceImpl(new EventType[] { windowType },
            new String[] { windowName }, new boolean[] { true }, services.getEngineURI(), false);
    ResultSetProcessor resultSetProcessor = ResultSetProcessorFactory.getProcessor(statementSpec,
            statementContext, typeService, null, new boolean[0], true);

    // Attach output view
    OutputProcessView outputView = OutputProcessViewFactory.makeView(resultSetProcessor, statementSpec,
            statementContext, services.getInternalEventRouter());
    finalView.addView(outputView);
    finalView = outputView;

    // Handle insert case
    if (statementSpec.getCreateWindowDesc().isInsert() && !isRecoveringStatement) {
        String insertFromWindow = statementSpec.getCreateWindowDesc().getInsertFromWindow();
        NamedWindowProcessor sourceWindow = services.getNamedWindowService().getProcessor(insertFromWindow);
        List<EventBean> events = new ArrayList<EventBean>();
        if (statementSpec.getCreateWindowDesc().getInsertFilter() != null) {
            EventBean[] eventsPerStream = new EventBean[1];
            ExprEvaluator filter = statementSpec.getCreateWindowDesc().getInsertFilter().getExprEvaluator();
            for (Iterator<EventBean> it = sourceWindow.getTailView().iterator(); it.hasNext();) {
                EventBean candidate = it.next();
                eventsPerStream[0] = candidate;
                Boolean result = (Boolean) filter.evaluate(eventsPerStream, true, statementContext);
                if ((result == null) || (!result)) {
                    continue;
                }
                events.add(candidate);
            }
        } else {
            for (Iterator<EventBean> it = sourceWindow.getTailView().iterator(); it.hasNext();) {
                events.add(it.next());
            }
        }
        if (events.size() > 0) {
            EventType rootViewType = rootView.getEventType();
            EventBean[] convertedEvents = services.getEventAdapterService().typeCast(events, rootViewType);
            rootView.update(convertedEvents, null);
        }
    }

    log.debug(".start Statement start completed");

    return new EPStatementStartResult(finalView, stopMethod);
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@Interceptors({ ServiceProviderInterceptor.class })
public boolean searchLdapUsersOverLimit(final String userIdPattern) throws ValidationException {
    ArgumentValidator.notNull("userIdPattern", userIdPattern);

    Organization organization = dm.getCurrentUser().getOrganization();

    LdapConnector connector = getLdapConnectionForOrganization(organization);
    Properties dirProperties = connector.getDirProperties();
    Map<SettingType, String> attrMap = connector.getAttrMap();
    String baseDN = connector.getBaseDN();
    ILdapResultMapper<VOUserDetails> mapper = new LdapVOUserDetailsMapper(null, attrMap);
    try {//from ww w. j  av  a 2s  .c o m
        return ldapAccess.searchOverLimit(dirProperties, baseDN, getLdapSearchFilter(attrMap, userIdPattern),
                mapper, false);
    } catch (NamingException e) {
        Object[] params = new Object[] { dirProperties.get(Context.PROVIDER_URL), e.getMessage() };
        ValidationException vf = new ValidationException(ReasonEnum.LDAP_CONNECTION_REFUSED, null, params);
        logger.logError(Log4jLogger.SYSTEM_LOG, vf, LogMessageIdentifier.ERROR_LDAP_SYSTEM_CONNECTION_REFUSED);
        throw vf;
    }
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

@Override
@Interceptors({ ServiceProviderInterceptor.class })
public List<VOUserDetails> searchLdapUsers(final String userIdPattern) throws ValidationException {

    ArgumentValidator.notNull("userIdPattern", userIdPattern);

    Organization organization = dm.getCurrentUser().getOrganization();

    LdapConnector connector = getLdapConnectionForOrganization(organization);
    Properties dirProperties = connector.getDirProperties();
    Map<SettingType, String> attrMap = connector.getAttrMap();
    String baseDN = connector.getBaseDN();

    List<SettingType> attrList = new ArrayList<>(attrMap.keySet());
    ILdapResultMapper<VOUserDetails> mapper = new LdapVOUserDetailsMapper(null, attrMap);
    try {//from  ww  w  .java  2s  .c  om
        // read user from LDAP
        List<VOUserDetails> voUserList = ldapAccess.search(dirProperties, baseDN,
                getLdapSearchFilter(attrMap, userIdPattern), mapper, false);

        int size = voUserList.size();
        for (int i = 0; i < size; i++) {
            VOUserDetails voUser = voUserList.get(i);
            PlatformUser user = getPlatformUserByOrgAndReamUserId(organization, voUser.getRealmUserId());
            if (null != user) {
                // update the domain object with possibly changed LDAP
                // attributes and return a complete value object
                UserDataAssembler.updatePlatformUser(voUser, attrList, user);
                voUserList.set(i, UserDataAssembler.toVOUserDetails(user));
            } else {
                // set some mandatory attributes
                voUser.setOrganizationId(organization.getOrganizationId());
                String locale = voUser.getLocale();
                if (locale == null || locale.trim().length() == 0) {
                    voUser.setLocale(organization.getLocale());
                }
            }
        }
        return voUserList;
    } catch (NamingException e) {
        Object[] params = new Object[] { dirProperties.get(Context.PROVIDER_URL), e.getMessage() };
        ValidationException vf = new ValidationException(ReasonEnum.LDAP_CONNECTION_REFUSED, null, params);
        logger.logError(Log4jLogger.SYSTEM_LOG, vf, LogMessageIdentifier.ERROR_LDAP_SYSTEM_CONNECTION_REFUSED);
        throw vf;
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * @param userName Username of the user.
 * @param searchBase Searchbase which the user should be searched for.
 * @param searchFilter Search filter of the username.
 * @return DN of the user whose usename is given.
 * @throws UserStoreException If an error occurs while connecting to the LDAP userstore.
 *//*from   w w w .jav  a  2s .  c  om*/
private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter)
        throws UserStoreException {
    boolean debug = log.isDebugEnabled();

    String userDN = null;

    DirContext dirContext = this.connectionSource.getContext();
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        if (log.isDebugEnabled()) {
            try {
                log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                        + dirContext.getNameInNamespace());
            } catch (NamingException e) {
                log.debug("Error while getting DN of search base", e);
            }
        }
        SearchResult userObj;
        String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String base : searchBases) {
            answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls);
            if (answer.hasMore()) {
                userObj = answer.next();
                if (userObj != null) {
                    //no need to decode since , if decoded the whole string, can't be encoded again
                    //eg CN=Hello\,Ok=test\,test, OU=Industry
                    userDN = userObj.getNameInNamespace();
                    break;
                }
            }
        }
        if (debug) {
            log.debug("Name in space for " + userName + " is " + userDN);
        }
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userDN;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 *
 *//*from   w  w  w. ja  v a2s  .co  m*/
public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    String failedUserDN = null;

    if (userName == null || credential == null) {
        return false;
    }

    userName = userName.trim();

    String password = (String) credential;
    password = password.trim();

    if (userName.equals("") || password.equals("")) {
        return false;
    }

    if (debug) {
        log.debug("Authenticating user " + userName);
    }

    boolean bValue = false;
    // check cached user DN first.
    String name = null;
    LdapName ldn = (LdapName) userCache.get(userName);
    if (ldn != null) {
        name = ldn.toString();
        try {
            if (debug) {
                log.debug("Cache hit. Using DN " + name);
            }
            bValue = this.bindAsUser(userName, name, (String) credential);
        } catch (NamingException e) {
            // do nothing if bind fails since we check for other DN
            // patterns as well.
            if (log.isDebugEnabled()) {
                log.debug("Checking authentication with UserDN " + name + "failed " + e.getMessage(), e);
            }
        }

        if (bValue) {
            return bValue;
        }
        // we need not check binding for this name again, so store this and check
        failedUserDN = name;

    }
    // read DN patterns from user-mgt.xml
    String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

    if (patterns != null && !patterns.isEmpty()) {

        if (debug) {
            log.debug("Using UserDNPatterns " + patterns);
        }

        // if the property is present, split it using # to see if there are
        // multiple patterns specified.
        String[] userDNPatternList = patterns.split("#");
        if (userDNPatternList.length > 0) {
            for (String userDNPattern : userDNPatternList) {
                name = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
                // check if the same name is found and checked from cache
                if (failedUserDN != null && failedUserDN.equalsIgnoreCase(name)) {
                    continue;
                }

                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                try {
                    if (name != null) {
                        bValue = this.bindAsUser(userName, name, (String) credential);
                        if (bValue) {
                            LdapName ldapName = new LdapName(name);
                            userCache.put(userName, ldapName);
                            break;
                        }
                    }
                } catch (NamingException e) {
                    // do nothing if bind fails since we check for other DN
                    // patterns as well.
                    if (log.isDebugEnabled()) {
                        log.debug("Checking authentication with UserDN " + userDNPattern + "failed "
                                + e.getMessage(), e);
                    }
                }
            }
        }
    } else {
        name = getNameInSpaceForUserName(userName);
        try {
            if (name != null) {
                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                bValue = this.bindAsUser(userName, name, (String) credential);
                if (bValue) {
                    LdapName ldapName = new LdapName(name);
                    userCache.put(userName, ldapName);
                }
            }
        } catch (NamingException e) {
            String errorMessage = "Cannot bind user : " + userName;
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
            throw new UserStoreException(errorMessage, e);
        }
    }

    return bValue;
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Return an InputStream to an HTML representation of the contents
 * of this directory.//from  w  ww. j  ava2 s  .com
 *
 * @param contextPath     Context path to which our internal paths are
 *                        relative
 * @param resourceInfo    Description of the Parameter
 * @param xsltInputStream Description of the Parameter
 * @return Description of the Return Value
 */
protected InputStream renderXml(String contextPath, ResourceInfo resourceInfo, InputStream xsltInputStream) {

    StringBuffer sb = new StringBuffer();

    sb.append("<?xml version=\"1.0\"?>");
    sb.append("<listing ");
    sb.append(" contextPath='");
    sb.append(contextPath);
    sb.append("'");
    sb.append(" directory='");
    sb.append(resourceInfo.path);
    sb.append("' ");
    sb.append(" hasParent='").append(!resourceInfo.path.equals("/"));
    sb.append("'>");

    sb.append("<entries>");

    try {

        // Render the directory entries within this directory
        DirContext directory = resourceInfo.directory;
        NamingEnumeration enum1 = resourceInfo.resources.list(resourceInfo.path);
        while (enum1.hasMoreElements()) {

            NameClassPair ncPair = (NameClassPair) enum1.nextElement();
            String resourceName = ncPair.getName();
            ResourceInfo childResourceInfo = new ResourceInfo(resourceName, directory);

            String trimmed = resourceName;
            if (trimmed.equalsIgnoreCase("WEB-INF") || trimmed.equalsIgnoreCase("META-INF")
                    || trimmed.equalsIgnoreCase(localXsltFile)) {
                continue;
            }

            sb.append("<entry");
            sb.append(" type='").append(childResourceInfo.collection ? "dir" : "file").append("'");
            sb.append(" urlPath='").append(rewriteUrl(contextPath))
                    .append(rewriteUrl(resourceInfo.path + resourceName))
                    .append(childResourceInfo.collection ? "/" : "").append("'");
            if (!childResourceInfo.collection) {
                sb.append(" size='").append(renderSize(childResourceInfo.length)).append("'");
            }
            sb.append(" date='").append(childResourceInfo.httpDate).append("'");

            sb.append(">");
            sb.append(trimmed);
            if (childResourceInfo.collection) {
                sb.append("/");
            }
            sb.append("</entry>");

        }

    } catch (NamingException e) {
        // Something went wrong
        e.printStackTrace();
    }

    sb.append("</entries>");

    String readme = getReadme(resourceInfo.directory);

    if (readme != null) {
        sb.append("<readme><![CDATA[");
        sb.append(readme);
        sb.append("]]></readme>");
    }

    sb.append("</listing>");

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Source xmlSource = new StreamSource(new StringReader(sb.toString()));
        Source xslSource = new StreamSource(xsltInputStream);
        Transformer transformer = tFactory.newTransformer(xslSource);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
        StreamResult out = new StreamResult(osWriter);
        transformer.transform(xmlSource, out);
        osWriter.flush();
        return (new ByteArrayInputStream(stream.toByteArray()));
    } catch (Exception e) {
        log("directory transform failure: " + e.getMessage());
        return renderHtml(contextPath, resourceInfo);
    }
}