Example usage for java.util Hashtable putAll

List of usage examples for java.util Hashtable putAll

Introduction

In this page you can find the example usage for java.util Hashtable putAll.

Prototype

public synchronized void putAll(Map<? extends K, ? extends V> t) 

Source Link

Document

Copies all of the mappings from the specified map to this hashtable.

Usage

From source file:it.greenvulcano.jmx.impl.KarafJMXEntryPoint.java

private ObjectName calculateMBeanName(Object mbean, MBeanServer mserver, Map<String, String> properties,
        String descriptorName) throws Exception {
    String domain = mserver.getDefaultDomain();

    Hashtable<String, String> keyProperties = new Hashtable<String, String>();
    if (properties != null) {
        keyProperties.putAll(properties);
    }// w  w  w  .  java 2 s.c  o m

    if (objectNameBuilders != null) {
        for (int i = 0; i < objectNameBuilders.size(); i++) {
            ObjectNameBuilder onb = objectNameBuilders.get(i);
            keyProperties = onb.resolve(descriptorName, keyProperties, mbean);
        }
    }

    ObjectName oname = new ObjectName(domain, keyProperties);

    return oname;
}

From source file:it.greenvulcano.jmx.impl.KarafJMXEntryPoint.java

private ObjectName calculateObjectName(Object object, MBeanServer mserver, ManagedBean managed,
        Map<String, String> properties, String descriptorName) throws Exception {
    String domain = managed.getDomain();
    if (domain == null) {
        domain = mserver.getDefaultDomain();
    }//  w  ww.ja  v a 2 s  .co m

    String name = managed.getName();
    String className = managed.getClassName();
    String group = managed.getGroup();
    String type = managed.getType();

    Hashtable<String, String> keyProperties = new Hashtable<String, String>();
    keyProperties.put("Name", name);
    keyProperties.put("Class", className);
    keyProperties.put("Group", group);
    keyProperties.put("Type", type);
    if (properties != null) {
        keyProperties.putAll(properties);
    }

    if (objectNameBuilders != null) {
        for (int i = 0; i < objectNameBuilders.size(); i++) {
            ObjectNameBuilder onb = objectNameBuilders.get(i);
            keyProperties = onb.resolve(descriptorName, keyProperties, object);
        }
    }

    ObjectName oname = new ObjectName(domain, keyProperties);

    return oname;
}

From source file:com.mirth.connect.connectors.jms.JmsConnector.java

protected void initJndiContext() throws NamingException, InitialisationException {
    if (jndiContext == null) {
        Hashtable props = new Hashtable();

        if (jndiInitialFactory != null) {
            props.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialFactory);
        } else if (jndiProviderProperties == null
                || !jndiProviderProperties.containsKey(Context.INITIAL_CONTEXT_FACTORY)) {
            throw new InitialisationException(new Message(Messages.X_IS_NULL, "jndiInitialFactory"), this);
        }/* ww w.j  a va2 s . c o m*/

        if (jndiProviderUrl != null) {
            props.put(Context.PROVIDER_URL, replacer.replaceValues(jndiProviderUrl));
        }

        if (jndiProviderProperties != null) {
            props.putAll(jndiProviderProperties);
        }
        jndiContext = new InitialContext(props);
    }
}

From source file:com.clustercontrol.ping.factory.RunMonitorPing.java

/**
 * ping???// ww  w  . j a v  a 2s  .  c  o  m
 * <p>
 * <ol>
 * <li>fping?????RunMonitor?runMonitorInfooverride???</li>
 * <li>????????{@link #setMonitorInfo(String, String)}</li>
 * <li>?????????{@link #setJudgementInfo()}</li>
 * <li>??????????{@link #setCheckInfo()}</li>
 * <li>??????? {@link #collect(String)}</li>
 * <li>???????? {@link #getCheckResult(boolean)}</li>
 * <li>?????????{@link #getPriority(int)}</li>
 * <li>????{@link #notify(boolean, String, int, Date)}</li>
 * </ol>
 * 
 * @return ??????</code> true </code>
 * @throws MonitorNotFound
 * @throws HinemosUnknown
 * 
 * @see #setMonitorInfo(String, String)
 * @see #setJudgementInfo()
 * @see #setCheckInfo()
 * @see #collect(String)
 * @see #getCheckResult(boolean)
 * @see #getPriority(int)
 * @see #notify(boolean, String, int, Date)
 */
@Override
protected boolean runMonitorInfo() throws MonitorNotFound, HinemosUnknown {

    m_now = HinemosTime.getDateInstance();
    m_priorityMap = new HashMap<Integer, ArrayList<String>>();
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_INFO), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_WARNING), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_CRITICAL), new ArrayList<String>());
    m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_UNKNOWN), new ArrayList<String>());

    List<Sample> sampleList = new ArrayList<Sample>();

    // 
    boolean run = this.setMonitorInfo(m_monitorTypeId, m_monitorId);
    if (!run) {
        // ?
        return true;
    }

    // 
    setJudgementInfo();

    // ??
    setCheckInfo();

    // ID?????
    ArrayList<String> facilityList = new RepositoryControllerBean().getExecTargetFacilityIdList(m_facilityId,
            m_monitor.getOwnerRoleId());
    if (facilityList.size() == 0)
        return true;

    // ??
    ArrayList<Integer> priorityList = new ArrayList<Integer>();

    // ???
    Sample sample = null;
    if (m_monitor.getCollectorFlg()) {
        sample = new Sample(HinemosTime.getDateInstance(), m_monitor.getMonitorId());
    }

    //fping?false??ver2.2?????ping?
    if (!PingProperties.isFpingEnable()) {

        String facilityId = null;
        for (int index = 0; index < facilityList.size(); index++) {
            facilityId = facilityList.get(index);
            if (facilityId != null && !"".equals(facilityId)) {

                // ?
                boolean ret = collect(facilityId);

                // ??
                int checkResult = getCheckResult(ret);

                // ??
                if (m_nodeDate > m_scopeDate) {
                    m_scopeDate = m_nodeDate;
                }

                // ??
                // ??
                if (!m_isMonitorJob) {
                    notify(true, facilityId, checkResult, new Date(m_nodeDate));
                } else {
                    m_monitorRunResultInfo = new MonitorRunResultInfo();
                    MonitorJudgementInfo info = m_judgementInfoList.get(checkResult);
                    if (info != null) {
                        m_monitorRunResultInfo.setPriority(info.getPriority());
                    } else {
                        m_monitorRunResultInfo.setPriority(m_failurePriority);
                    }
                    m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message));
                    m_monitorRunResultInfo.setNodeDate(m_nodeDate);
                }

                // ??
                if (sample != null) {
                    int errorCode = -1;
                    if (ret) {
                        errorCode = CollectedDataErrorTypeConstant.NOT_ERROR;
                    } else {
                        errorCode = CollectedDataErrorTypeConstant.UNKNOWN;
                    }
                    sample.set(facilityId, m_monitor.getItemName(), m_value, errorCode);
                }
            }
        }
    } //fping?true????ping?
    else {
        //    ?
        //   fping?????????ping???
        boolean ret = collectFping(facilityList, priorityList);

        if (ret) {
            Hashtable<String, PingResult> fpingResultSet = new Hashtable<String, PingResult>();
            Hashtable<String, PingResult> fpingResultSetV6 = new Hashtable<String, PingResult>();
            //????
            if (m_MsgErr != null) {
                fpingResultSet = wrapUpFping(m_MsgErr, m_runCount, 4);
            }
            if (m_MsgErrV6 != null) {
                m_log.debug("runMonitorInfo(): fpingResultSetV6 check");
                fpingResultSetV6 = wrapUpFping(m_MsgErrV6, m_runCount, 6);
            }

            //IPv4????????IPv6?????
            m_log.debug("runMonitorInfo(): before fpingResultSet check");
            if (fpingResultSet.size() == 0) {
                m_log.debug("runMonitorInfo(): after fpingResultSet check");
                fpingResultSet = fpingResultSetV6;
            }
            //IPv4??????IPv6??
            else if (fpingResultSetV6.size() != 0) {
                fpingResultSet.putAll(fpingResultSetV6);
            }

            //?????IP?
            Iterator<String> it = facilityList.iterator();

            String targetFacility;
            PingResult nodeResult;
            String[] node;

            while (it.hasNext()) {

                //??FacilityId?
                targetFacility = it.next();
                //???IP?
                node = m_Target.get(targetFacility);

                // ??????(IP?)??
                if (node != null) {

                    m_log.debug("runMonitorInfo(): before fpingResultSet.get()");
                    nodeResult = fpingResultSet.get(node[0]);

                    if (nodeResult == null) {
                        m_log.debug("runMonitorInfo(): after fpingResultSet.get()");

                        /* fping??????*/
                        String[] args = { m_monitorId };
                        String logMsg = "";
                        if (m_MsgErr != null) {
                            logMsg = m_MsgErr.toString();
                        }
                        if (m_MsgErrV6 != null) {
                            logMsg += " , " + m_MsgErrV6.toString();
                        }
                        AplLogger.put(PriorityConstant.TYPE_CRITICAL, HinemosModuleConstant.MONITOR_PING,
                                MessageConstant.MESSAGE_SYS_001_MON_PNG, args, logMsg);
                        m_log.info("Fping no response.");

                        /* fping??????*/
                        sample.set(targetFacility, m_monitor.getItemName(), Double.NaN,
                                CollectedDataErrorTypeConstant.UNKNOWN);
                    } else {

                        //??????????
                        m_lost = nodeResult.getLost();
                        //?????msec(long)?????
                        m_average = (long) nodeResult.getAverage();
                        m_message = nodeResult.getMesseage();
                        m_messageOrg = nodeResult.getMesseageOrg();
                        m_value = m_average;

                        if (m_log.isDebugEnabled()) {
                            m_log.debug("runMonitorInfo() monitorId = " + m_monitorId + ", facilityId = "
                                    + targetFacility + ", average = " + nodeResult.getAverage() + ", value = "
                                    + m_value);
                        }

                        // ??
                        int checkResult;
                        // ??????
                        if (m_lost == -1) {
                            checkResult = getCheckResult(false);
                        } else {
                            checkResult = getCheckResult(true);
                        }
                        boolean collectorResult = true;
                        if (m_lost == -1 || m_lost == 100) {
                            collectorResult = false;
                        }

                        // ??
                        if (m_nodeDate > m_scopeDate) {
                            m_scopeDate = m_nodeDate;
                        }

                        // ??
                        // ??
                        if (!m_isMonitorJob) {
                            notify(true, targetFacility, checkResult, new Date(m_nodeDate));
                        } else {
                            m_monitorRunResultInfo = new MonitorRunResultInfo();
                            m_monitorRunResultInfo.setPriority(checkResult);
                            m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message));
                            m_monitorRunResultInfo.setNodeDate(m_nodeDate);
                        }

                        // ??
                        if (sample != null) {
                            int errorCode = -1;
                            if (collectorResult) {
                                errorCode = CollectedDataErrorTypeConstant.NOT_ERROR;
                            } else {
                                errorCode = CollectedDataErrorTypeConstant.UNKNOWN;
                            }
                            sample.set(targetFacility, m_monitor.getItemName(),
                                    (double) nodeResult.getAverage(), errorCode);
                        }
                    }
                }
            }
        }
    }
    // ?????
    if (sample != null) {
        sampleList.add(sample);
    }
    if (!sampleList.isEmpty()) {
        CollectDataUtil.put(sampleList);
    }
    return true;
}

From source file:hu.sztaki.lpds.pgportal.services.asm.ASMService.java

/**
 * /*from www.  j  ava  2s .  c om*/
 * Gets and returns detailed informations about a workflow (e.g. statuses of the current workflow instance, overall
 * statistics)
 * 
 * @param userID
 *            - ID of the user
 * @param workflowID
 *            - ID of the workflow
 * @return WorkflowInstanceBean object that contains information
 * @throws ASM_NoValidRuntimeIDException
 *             -it's thrown if there is No valid runtime ID
 */

public WorkflowInstanceBean getDetails(String userID, String workflowID) throws ASM_NoValidRuntimeIDException {

    String runtimeID = (String) PortalCacheService.getInstance().getUser(userID).getWorkflow(workflowID)
            .getAllRuntimeInstance().keys().nextElement();
    if (runtimeID != null) {

        if (PortalCacheService.getInstance().getUser(userID).getWorkflow(workflowID).getRuntime(runtimeID)
                .getJobsStatus().isEmpty()) {
            Hashtable prp = new Hashtable();
            prp.put("url", PortalCacheService.getInstance().getUser(userID).getWorkflow(workflowID).getWfsID());
            ServiceType st = InformationBase.getI().getService("wfs", "portal", prp, new Vector());
            try {
                PortalWfsClient pc = (PortalWfsClient) Class.forName(st.getClientObject()).newInstance();
                pc.setServiceURL(st.getServiceUrl());
                pc.setServiceID(st.getServiceID());
                ComDataBean cmb = new ComDataBean();
                cmb.setPortalID(PropertyLoader.getInstance().getProperty("service.url"));
                cmb.setUserID(userID);
                cmb.setWorkflowID(workflowID);
                cmb.setWorkflowRuntimeID(runtimeID);
                int getmax = 2500;
                long cnt = 0;
                int retCnt = getmax;

                while (retCnt == getmax) {
                    cmb.setSize(cnt);

                    Vector<JobInstanceBean> retVector = new Vector<JobInstanceBean>();
                    retVector = pc.getWorkflowInstanceJobs(cmb);
                    // //System.out.println("wspgrade doInstanceDetails retVector.size() : " + retVector.size());
                    for (int i = 0; i < retVector.size(); i++) {
                        JobInstanceBean tmp = retVector.get(i);
                        // //System.out.println("wspgrade doInstanceDetails tmp : " + tmp.getJobID() +", "+
                        // tmp.getPID() +", "+ tmp.getStatus() +", "+ tmp.getResource());
                        PortalCacheService.getInstance().getUser(userID).getWorkflow(workflowID)
                                .getRuntime(runtimeID).addJobbStatus(tmp.getJobID(), "" + tmp.getPID(),
                                        "" + tmp.getStatus(), tmp.getResource(), -1);
                    }
                    //
                    retCnt = retVector.size();
                    cnt++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        WorkflowInstanceBean workflowinstance = new WorkflowInstanceBean();

        // first key : jobname, second key : status code , second value : instancenumber
        UserData userdata = PortalCacheService.getInstance().getUser(userID);
        WorkflowData workflowdata = userdata.getWorkflow(workflowID);
        WorkflowRunTime runtimedata = workflowdata.getRuntime(runtimeID);
        Hashtable<String, Hashtable<String, String>> jobinstances = runtimedata.getCollectionJobsStatus();

        Iterator jobiterator = jobinstances.keySet().iterator();
        while (jobiterator.hasNext()) {

            String jobname = (String) jobiterator.next();

            RunningJobDetailsBean jobinstance = new RunningJobDetailsBean();
            jobinstance.setName(jobname);

            Hashtable<String, String> statuses = jobinstances.get(jobname);
            Iterator overviewstatusit = statuses.keySet().iterator();
            while (overviewstatusit.hasNext()) {
                String status = overviewstatusit.next().toString();

                // Integer status = Integer.parseInt((String)overviewstatusit.next().toString());

                OverviewJobStatusBean overview = new OverviewJobStatusBean();
                overview.setStatuscode(status);
                overview.setNumberofinstances(statuses.get(status));
                jobinstance.getStatisticsBean().getOverviewedstatuses().add(overview);
            }

            // first key : pid value : JobStatusData
            Hashtable<String, JobStatusData> runtimeinstances = new Hashtable<String, JobStatusData>();
            // runtimedata.getJobStatus("" + jobname).putAll(runtimeinstances);
            runtimeinstances.putAll(runtimedata.getJobStatus("" + jobname));
            Iterator instanceiterator = runtimeinstances.keySet().iterator();
            while (instanceiterator.hasNext()) {
                ASMJobInstanceBean instance = new ASMJobInstanceBean();

                String instanceID = (String) instanceiterator.next();
                String pid = runtimeinstances.get(instanceID).getPid();
                String resource = runtimeinstances.get(instanceID).getResource();
                String status = Integer.toString(runtimeinstances.get(instanceID).getStatus());
                String stdout = this.getStdOutFile(userID, workflowID, jobname, pid, runtimeID);

                String stderr = this.getStdErrFile(userID, workflowID, jobname, pid, runtimeID);

                String systemlog = this.getSystemLogFile(userID, workflowID, jobname, pid, runtimeID);

                instance.setId(instanceID);
                instance.setStatus(status);
                instance.setErrorText(stderr);
                instance.setOutputText(stdout);
                instance.setLogbookText(systemlog);
                instance.setUsedResource(resource);
                jobinstance.getInstances().add(instance);
            }
            workflowinstance.getJobs().add(jobinstance);
        }
        return workflowinstance;
    } else {
        throw new ASM_NoValidRuntimeIDException();
    }

}

From source file:com.clustercontrol.nodemap.session.NodeMapControllerBean.java

/**
 * fping?ping?????<BR>//from  ww w  .  j  a  v  a  2  s .  c  o m
 * @param facilityId Ping?ID()collect?facilityID???
 * @return ping??
 * @throws HinemosUnknown
 * @throws NodeMapException 
 */
public List<String> pingToFacilityList(List<String> facilityList) throws HinemosUnknown, NodeMapException {

    String message = "";
    String messageOrg = "";
    //??????
    // hosts[] IP(String ??)
    // hostsv6[]  IPv6(String??)
    // node     IP????
    // target   nodo?
    HashSet<String> hosts = new HashSet<String>();
    HashSet<String> hostsv6 = new HashSet<String>();
    // ip?name
    Hashtable<String, List<String>> facilityNameTable = new Hashtable<>();

    String facilityId = null;
    int version = 4;
    String[] node;
    for (int index = 0; index < facilityList.size(); index++) {
        facilityId = facilityList.get(index);
        if (facilityId != null && !"".equals(facilityId)) {
            node = new String[2];
            try {

                // ??
                NodeInfo info = new RepositoryControllerBean().getNode(facilityId);

                if (info.getIpAddressVersion() != null) {
                    version = info.getIpAddressVersion();
                } else {
                    version = 4;
                }

                if (version == 6) {

                    InetAddress[] ip = InetAddress.getAllByName(info.getIpAddressV6());

                    if (ip.length != 1) {
                        //IPInetAddress??????1????????
                        //UnnownHostExcption
                        UnknownHostException e = new UnknownHostException();
                        m_log.info("pingToFacilityList() : " + e.getClass().getSimpleName() + ", "
                                + e.getMessage());
                        throw e;
                    }

                    node[0] = ip[0].getHostAddress();
                    if (node[0] != null && !node[0].equals("")) {
                        //IPHashSet?????
                        hostsv6.add(node[0]);
                    }
                } else {
                    node[0] = info.getIpAddressV4();
                    if (node[0] != null && !node[0].equals("")) {

                        //IPHashSet?????
                        hosts.add(node[0]);
                    }
                }
                if (node[0] != null && !node[0].equals("")) {
                    node[1] = info.getNodeName();
                    //target??????
                    List<String> facilitys = facilityNameTable.get(node[0]);
                    if (facilitys == null) {
                        facilitys = new ArrayList<>();
                    }
                    facilitys.add(facilityId);
                    facilityNameTable.put(node[0], facilitys);
                }
            } catch (FacilityNotFound e) {
                message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage() + ","
                        + facilityId;
                messageOrg = e.getMessage();
                throw new NodeMapException(message + ", " + messageOrg, e);
            } catch (UnknownHostException e) {
                // ???
            }
        }
    }

    int runCount = 0;
    int runInterval = 0;
    int pingTimeout = 0;
    try {
        // [](default:1?19)
        String runCountKey = "nodemap.ping.runcount";
        runCount = HinemosPropertyUtil
                .getHinemosPropertyNum(runCountKey, Long.valueOf(PingRunCountConstant.TYPE_COUNT_01))
                .intValue();
        CommonValidator.validateInt(runCountKey, runCount, 1, 9);

        // [ms](default:1000?05000)
        String runIntervalKey = "nodemap.ping.runinterval";
        runInterval = HinemosPropertyUtil
                .getHinemosPropertyNum(runIntervalKey, Long.valueOf(PingRunIntervalConstant.TYPE_SEC_02))
                .intValue();
        CommonValidator.validateInt(runIntervalKey, runInterval, 0, 5 * 1000);

        // [ms](default:5000?13600000)
        String pintTimeoutKey = "nodemap.ping.timeout";
        pingTimeout = HinemosPropertyUtil
                .getHinemosPropertyNum(pintTimeoutKey, Long.valueOf(PingRunIntervalConstant.TYPE_SEC_05))
                .intValue();
        CommonValidator.validateInt(pintTimeoutKey, pingTimeout, 1, 60 * 60 * 1000);
    } catch (Exception e) {
        m_log.warn("pingToFacilityList() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        throw new HinemosUnknown(e.getMessage(), e);
    }

    ReachAddressFping reachabilityFping = new ReachAddressFping(runCount, runInterval, pingTimeout);

    boolean result = true;
    boolean resultTmp = true;
    ArrayList<String> msgErr = new ArrayList<>();
    ArrayList<String> msgErrV6 = new ArrayList<>();
    Hashtable<String, PingResult> fpingResultSet = new Hashtable<String, PingResult>();
    Hashtable<String, PingResult> fpingResultSetV6 = new Hashtable<String, PingResult>();

    RunMonitorPing monitorPing = new RunMonitorPing();
    //IPv4???fping??
    if (hosts.size() != 0) {
        result = reachabilityFping.isReachable(hosts, 4);
        msgErr = reachabilityFping.getM_errMsg();
    }
    //IPv6???fping6??
    if (hostsv6.size() != 0) {
        resultTmp = reachabilityFping.isReachable(hostsv6, 6);
        msgErrV6 = reachabilityFping.getM_errMsg();
    }

    if (!result || !resultTmp) {
        return null;
    }
    List<String> retList = new ArrayList<>();
    fpingResultSet = monitorPing.wrapUpFping(msgErr, runCount, 4);
    fpingResultSetV6 = monitorPing.wrapUpFping(msgErrV6, runCount, 6);
    //IPv4????????IPv6?????
    m_log.debug("pingToFacilityList(): before fpingResultSet check");
    if (fpingResultSet.size() == 0) {
        m_log.debug("pingToFacilityList(): after fpingResultSet check");
        fpingResultSet = fpingResultSetV6;
    }
    //IPv4??????IPv6??
    else if (fpingResultSetV6.size() != 0) {
        fpingResultSet.putAll(fpingResultSetV6);
    }
    for (Map.Entry<String, List<String>> ipAdd : facilityNameTable.entrySet()) {
        PingResult pingResult = fpingResultSet.get(ipAdd.getKey());
        for (String facility : ipAdd.getValue()) {
            retList.add(facility + " : " + pingResult.getMesseageOrg());
        }
    }
    return retList;
}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

/**
 * Sets up the environment parameters for creating a new context.
 *
 * @return the Hashtable describing the base DirContext that will be created, minus the username/password if any.
 *//*from   w  w w.j  a va  2s .co  m*/
protected Hashtable getEnvironment() {
    Hashtable env = new Hashtable();

    env.put(Context.SECURITY_AUTHENTICATION, authenticationType);
    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (useConnectionPool) {
        env.put(CONNECTION_POOL_KEY, "true");
    }

    if ((extraEnvVars != null) && (extraEnvVars.size() > 0)) {
        env.putAll(extraEnvVars);
    }

    return env;
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

public InitialDirContext getDefaultIntialDirContext(int pageSize, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    Hashtable<String, String> env = new Hashtable<String, String>(defaultEnvironment.size());
    env.putAll(defaultEnvironment);
    return buildInitialDirContext(env, pageSize, diagnostic);
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

public InitialDirContext getInitialDirContext(String principal, String credentials,
        AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    if (diagnostic == null) {
        diagnostic = new AuthenticationDiagnostic();
    }/*from   w  w  w .j a  va 2 s  .c  o m*/

    if (principal == null) {
        // failed before we tried to do anything
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Null user name provided.", diagnostic);
    }

    if (principal.length() == 0) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty user name provided.", diagnostic);
    }

    if (credentials == null) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("No credentials provided.", diagnostic);
    }

    if (credentials.length() == 0) {
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, false, null);
        throw new AuthenticationException("Empty credentials provided.", diagnostic);
    }

    diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_VALIDATION, true, null);

    Hashtable<String, String> env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, principal);
    env.put(Context.SECURITY_CREDENTIALS, credentials);

    return buildInitialDirContext(env, 0, diagnostic);
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

public void afterPropertiesSet() throws Exception {
    logger.debug("after Properties Set");
    // Check Anonymous bind

    Hashtable<String, String> env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.remove(Context.SECURITY_PRINCIPAL);
    env.remove(Context.SECURITY_CREDENTIALS);
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }/*w  ww. jav  a 2  s .  c  o  m*/
    try {
        new InitialDirContext(env);

        logger.warn("LDAP server supports anonymous bind " + env.get(Context.PROVIDER_URL));
    } catch (javax.naming.AuthenticationException ax) {

    } catch (AuthenticationNotSupportedException e) {

    } catch (NamingException nx) {
        logger.error("Unable to connect to LDAP Server; check LDAP configuration", nx);
        return;
    }

    // Simple DN and password

    env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, "daftAsABrush");
    env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }
    try {

        new InitialDirContext(env);

        throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException ax) {
        logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (AuthenticationNotSupportedException e) {
        logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (NamingException nx) {
        logger.info("LDAP server does not support simple string user ids and invalid credentials at "
                + env.get(Context.PROVIDER_URL));
    }

    // DN and password

    env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, "cn=daftAsABrush,dc=woof");
    env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }
    try {

        new InitialDirContext(env);

        throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException ax) {
        logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (AuthenticationNotSupportedException e) {
        logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (NamingException nx) {
        logger.info("LDAP server does not support simple DN and invalid password at "
                + env.get(Context.PROVIDER_URL));
    }

    // Check more if we have a real principal we expect to work

    String principal = defaultEnvironment.get(Context.SECURITY_PRINCIPAL);
    if (principal != null) {
        // Correct principal invalid password

        env = new Hashtable<String, String>(authenticatedEnvironment.size());
        env.putAll(authenticatedEnvironment);
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, "sdasdasdasdasd123123123");
        if (isSSLSocketFactoryRequired()) {
            KeyStore trustStore = initTrustStore();
            AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
            env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
        }
        if (!checkedEnvs.contains(env)) {

            try {

                new InitialDirContext(env);

                throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL)
                        + " falls back to use anonymous bind for a known principal if  invalid security credentials are presented. This is not supported.");
            } catch (javax.naming.AuthenticationException ax) {
                logger.info(
                        "LDAP server does not fall back to anonymous bind for known principal and invalid credentials at "
                                + env.get(Context.PROVIDER_URL));
            } catch (AuthenticationNotSupportedException e) {
                logger.info("LDAP server does not support the required authentication mechanism");
            } catch (NamingException nx) {
                // already done
            }
            // Record this environment as checked so that we don't check it again on further restarts / other subsystem
            // instances
            checkedEnvs.add(env);
        }
    }
}