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:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *//*from  ww w.  j av a2 s.co m*/
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

        // Create a Session
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}

From source file:org.wso2.siddhi.extension.table.rdbms.RDBMSEventTable.java

@Override
protected void init(TableDefinition tableDefinition, ConfigReader configReader) {
    this.attributes = tableDefinition.getAttributeList();
    Annotation storeAnnotation = AnnotationHelper.getAnnotation(ANNOTATION_STORE,
            tableDefinition.getAnnotations());
    Annotation primaryKeys = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_PRIMARY_KEY,
            tableDefinition.getAnnotations());
    Annotation indices = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_INDEX,
            tableDefinition.getAnnotations());
    RDBMSTableUtils.validateAnnotation(primaryKeys);
    RDBMSTableUtils.validateAnnotation(indices);
    String jndiResourceName = storeAnnotation.getElement(ANNOTATION_ELEMENT_JNDI_RESOURCE);
    if (!RDBMSTableUtils.isEmpty(jndiResourceName)) {
        try {/*from   ww w  .  j a  v  a  2s .  co  m*/
            this.lookupDatasource(jndiResourceName);
        } catch (NamingException e) {
            throw new RDBMSTableException("Failed to lookup datasource with provided JNDI resource name '"
                    + jndiResourceName + "': " + e.getMessage(), e);
        }
    } else {
        this.initializeDatasource(storeAnnotation);
    }
    String tableName = storeAnnotation.getElement(ANNOTATION_ELEMENT_TABLE_NAME);
    this.tableName = RDBMSTableUtils.isEmpty(tableName) ? tableDefinition.getId() : tableName;
    try {
        if (this.queryConfigurationEntry == null) {
            this.queryConfigurationEntry = RDBMSTableUtils
                    .lookupCurrentQueryConfigurationEntry(this.dataSource);
        }
    } catch (CannotLoadConfigurationException e) {
        throw new RDBMSTableException("Failed to initialize DB Configuration entry for table '" + this.tableName
                + "': " + e.getMessage(), e);
    }
    if (!this.tableExists()) {
        this.createTable(storeAnnotation, primaryKeys, indices);
    }
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return the user dn of an ldap entry//  ww w  .j  a va2 s.c o m
 * 
 * search: base, filter, attrs, user, pass
 * @return
 */
protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter,
        String[] attributes) {
    SearchResult ret = null;
    Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11);
    bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    bindEnv.put(Context.PROVIDER_URL, getLdapUrl());

    // remove null attributes
    List<String> goodAttributes = new ArrayList<String>();
    for (String s : attributes) {
        if (s != null) {
            goodAttributes.add(s);
        }
    }

    // get the DN 
    DirContext authenticationContext;
    try {
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(1);
        ctls.setReturningObjFlag(true);
        ctls.setReturningAttributes(goodAttributes.toArray(new String[0]));
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Authenticate as  User and password  
        if (bindUser != null && bindPass != null) {
            log.debug("NBinding with credential as user: " + bindUser);
            bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser);
            bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass);
        }
        authenticationContext = new InitialDirContext(bindEnv);
        // %u, %d in baseDN are still expanded 
        NamingEnumeration<SearchResult> answer;
        try {
            answer = authenticationContext.search(base, filter, ctls);

            if (answer.hasMore()) {
                ret = (SearchResult) answer.next();
            }
        } catch (NamingException e) {
            log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage());
        }
        authenticationContext.close();
        return ret;

    } catch (NamingException e) {
        log.error("Error while creating context: " + e.getMessage());
        if (e.getCause() != null) {
            log.error("Error is: " + e.getCause().getMessage());
        }
        return null;
    }
}

From source file:org.teiid.rhq.plugin.VDBComponent.java

@Override
public Configuration loadResourceConfiguration() {

    ManagedComponent mcVdb = null;//from w  w  w.ja  v a2  s .co m
    try {
        mcVdb = ProfileServiceUtil.getManagedComponent(getConnection(), new org.jboss.managed.api.ComponentType(
                PluginConstants.ComponentType.VDB.TYPE, PluginConstants.ComponentType.VDB.SUBTYPE), this.name);
    } catch (NamingException e) {
        final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$
        LOG.error(msg, e);
    } catch (Exception e) {
        final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
        LOG.error(msg, e);
    }

    String vdbName = ProfileServiceUtil.getSimpleValue(mcVdb, "name", String.class);
    Integer vdbVersion = ProfileServiceUtil.getSimpleValue(mcVdb, "version", Integer.class);
    String vdbDescription = ProfileServiceUtil.getSimpleValue(mcVdb, "description", String.class);
    String vdbStatus = ProfileServiceUtil.getSimpleValue(mcVdb, "status", String.class);
    String connectionType = ProfileServiceUtil.getSimpleValue(mcVdb, "connectionType", String.class);
    String vdbURL = ProfileServiceUtil.getSimpleValue(mcVdb, "url", String.class);

    // Get plugin config map for models
    Configuration configuration = resourceContext.getPluginConfiguration();

    configuration.put(new PropertySimple("name", vdbName));
    configuration.put(new PropertySimple("version", vdbVersion));
    configuration.put(new PropertySimple("description", vdbDescription));
    configuration.put(new PropertySimple("status", vdbStatus));
    configuration.put(new PropertySimple("url", vdbURL));
    configuration.put(new PropertySimple("connectionType", connectionType));

    try {
        getTranslators(mcVdb, configuration);
    } catch (Exception e) {
        final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
        LOG.error(msg, e);
    }

    getModels(mcVdb, configuration);

    return configuration;

}

From source file:org.pepstock.jem.springbatch.tasks.JemTasklet.java

/**
 * Is called by SpringBatch framework to execute business logic.<br>
 * Prepares datasets (and the files and resources) which could be used from
 * implementation of this class.<br>
 * Loads JNDI context so all resources could be used by their name, defined
 * in JCL./*from  ww w.  jav  a  2  s .  co m*/
 * 
 * @param stepContribution step contribution, passed by SpringBatch core
 * @param chunkContext chunk context, passed by SpringBatch core
 * @return always the status returned by abstract method
 *         <code>executeByJem</code>
 * @throws SpringBatchException if a error occurs
 */
@Override
public final RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
        throws SpringBatchException {
    LogAppl.getInstance();

    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;
    boolean isAbended = false;

    SpringBatchSecurityManager batchSM = (SpringBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);

    RepeatStatus status = null;

    // extract stepContext because the step name is necessary
    StepContext stepContext = chunkContext.getStepContext();

    List<DataDescriptionImpl> dataDescriptionImplList = ImplementationsContainer.getInstance()
            .getDataDescriptionsByItem(stepContext.getStepName());

    // new initial context for JNDI
    InitialContext ic = null;

    try {
        ic = ContextUtils.getContext();
        // scans all datasource passed
        for (DataSource source : dataSourceList) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new SpringBatchException(SpringBatchMessage.JEMS016E);
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }
            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new SpringBatchException(SpringBatchMessage.JEMS017E, res.toString());
            }

            // all properties create all StringRefAddrs necessary
            Map<String, ResourceProperty> properties = res.getProperties();

            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getValue());
                    } else {
                        throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(), res);
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(),
                                    res);
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getValue());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, dataDescriptionImplList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with format {type]/[name]
            LogAppl.getInstance().emit(SpringBatchMessage.JEMS024I, res);
            ic.rebind(source.getName(), ref);
        }

        // check if I have resources which must be locked
        if (!dataDescriptionImplList.isEmpty()) {

            // binds all data description impl to JNDI context
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {

                // create reference for JNDI access
                Reference reference = new DataStreamReference();

                // load GDG information, solving the real name of relative
                // position
                GDGManager.load(ddImpl);
                // serialize data description object in XML format
                XStream xstream = new XStream();
                String xml = xstream.toXML(ddImpl);
                // add string xml reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));

                LogAppl.getInstance().emit(SpringBatchMessage.JEMS023I, ddImpl);
                // bind resource using data description name
                ic.rebind(ddImpl.getName(), reference);
            }
        }
        // execute business logic
        // executes the java class defined in JCL
        // setting the boolean to TRUE
        SetFields.applyByAnnotation(this);
        isExecutionStarted = true;
        batchSM.setInternalAction(false);
        status = this.run(stepContribution, chunkContext);
    } catch (NamingException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS043E, e);
    } catch (RemoteException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } catch (IOException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS044E, e, e.getMessage());
    } catch (Exception e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } finally {
        batchSM.setInternalAction(true);
        if (!dataDescriptionImplList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {
                try {
                    // commit the GDG index in the root
                    // if an exception, write on standard output of job
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);

                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(e.getMessage());
                    } else {
                        exceptions.append(e.getMessage()).append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
                if (exceptions.length() > 0 && !isAbended) {
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E,
                            StringUtils.center("ATTENTION", 40, "-"));
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, exceptions.toString());
                }

            }
        }
        for (DataSource source : dataSourceList) {
            if (source.getName() != null) {
                // unbinds all resources
                try {
                    ic.unbind(source.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
    return status;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from ww  w.j  av a 2 s.co  m
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from ww w .  java 2  s . com*/
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from  w  ww  .  ja  v a2  s  .  c  om
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * Return a S4J user if successful bind to ldap
 * null if user or password is wrong//www  .jav  a  2s.c om
 *      
 * TODO if I don't need to provision user on ldap,  I could avoid some of that stuff.. 
 * when binding, it retrieves imap/smtp server data to provision mail push
 * @param username
 * @param password
 * @return the {@link Sync4jUser} created from ldap fields
 */
public LDAPUser bindUserToLdap(String username, String password) {
    LDAPUser ldapUser = null;
    String userDN = null;
    LdapManagerInterface ldapBindInterface = null;
    /* TODO
     * this is now done creating an eventually authenticated context specified in 
     *  configuration file.
     *  moreover this context is shared between all ldap connections,
     *  so could be better defined at application server level 
     */
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        // use a bean configuration file
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(t.tmpLdapUrl, t.tmpBaseDn, getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // search the user binding with default ldap credential defined in the Officer.xml
            ldapInterface.setBaseDn(t.tmpBaseDn);
            SearchResult sr = ldapInterface.searchOneEntry(t.tmpUserSearch, new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr != null) {
                userDN = sr.getNameInNamespace().trim();
                log.info("binding with dn:" + userDN);
            } else {
                log.info("Username" + username + "not found");
                return null;
            }
        } else { // use append
            userDN = "uid=" + username + "," + baseDn;
        }

        ldapInterface.close();
        ldapBindInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapBindInterface.init(t.tmpLdapUrl, userDN, userDN, password, false, false, null);
        SearchResult sr = ldapBindInterface.searchOneEntry("(objectclass=*)", getLdapAttributesToRetrieve(),
                SearchControls.OBJECT_SCOPE);

        if (sr != null) {
            ldapUser = new LDAPUser();
            ldapUser.setUsername(username);
            ldapUser.setPassword(password);

            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_EMAIL))) {
                ldapUser.setEmail(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_EMAIL)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_FIRSTNAME))) {
                ldapUser.setFirstname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_FIRSTNAME)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_LASTNAME))) {
                ldapUser.setLastname(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_LASTNAME)));
            }

            // set attributes to be passed to LDAP and CalDAV connector
            ldapUser.setUserDn(userDN);
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_ADDRESSBOOK))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_ADDRESSBOOK)));
            }
            if (StringUtils.isNotEmpty(getAttributeMap().get(Constants.USER_CALENDAR))) {
                ldapUser.setPsRoot(
                        LdapUtils.getPrettyAttribute(sr, getAttributeMap().get(Constants.USER_CALENDAR)));
            }
        } else {
            return null;
        }

    } catch (SyncSourceException e1) {
        log.error("Can't instantiate context: " + e1.getMessage());
        ldapUser = null;
    } catch (NamingException e) {
        log.warn("Can't retrieve mailserver attributes from ldap: " + e.getMessage());
        ldapUser = null;
    } catch (LDAPAccessException e) {
        log.error("Can't instantiate context: " + e.getMessage());
        ldapUser = null;
    } finally {
        if (ldapInterface != null) {
            ldapInterface.close();
        }
        if (ldapBindInterface != null) {
            ldapBindInterface.close();
        }
    }

    return ldapUser;
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java

@Override
public boolean removeKey(String alias)
        throws CryptoTokenOfflineException, KeyStoreException, SignServerException {
    final KeyStore keyStore = getKeyStore();
    boolean result = CryptoTokenHelper.removeKey(keyStore, alias);
    if (result) {
        OutputStream out = null;/*  www . j a  va2s  .c  o m*/
        try {
            if (!TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
                out = new FileOutputStream(new File(keystorepath));
            } else {
                // use internal worker data
                out = new ByteArrayOutputStream();
            }
            keyStore.store(out, authenticationCode);

            if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) {
                final byte[] data = ((ByteArrayOutputStream) out).toByteArray();

                getWorkerSession().setKeystoreData(new AdminInfo("Internal", null, null), this.workerId, data);
            }

            readFromKeystore(null);
        } catch (NamingException ex) {
            LOG.error("Unable to lookup worker session: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (IOException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (NoSuchAlgorithmException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (CertificateException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (NoSuchProviderException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } catch (UnrecoverableKeyException ex) {
            LOG.error("Unable to persist new keystore after key removal: " + ex.getMessage(), ex);
            throw new SignServerException("Unable to persist key removal");
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
    return result;
}