Example usage for java.util Enumeration toString

List of usage examples for java.util Enumeration toString

Introduction

In this page you can find the example usage for java.util Enumeration toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

/**
 * Retrieves a user from LDAP//from w  ww .j  av a  2 s.  co  m
 */
public IUser getUser(String userID) throws EUsrGrpException {

    if (userID == null) {
        return null;
    }

    String userDN;

    if (userID.indexOf('=') < 0) { // user ID is not a DN
        userDN = getUserDN(userID);

    } else { // user ID is a DN
        // TODO: use a separate method for user ID and DN
        userDN = userID;
    }

    try {
        LDAPConnection ldapconn = null;

        try {
            ldapconn = getConn();

            // use base search to find the exact user
            LDAPSearchResults res = ldapconn.search(userDN, LDAPv2.SCOPE_BASE, "(objectclass=*)", null, false);

            // throw EUsrGrpException if result is empty
            Enumeration<IUser> e = buildUsers(res);

            // user found
            return e.nextElement();

        } finally {
            if (ldapconn != null)
                returnConn(ldapconn);
        }

    } catch (Exception e) {
        // currently this will catch all exceptions
        // TODO: catch user not found exception only, rethrow everything else
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_GET_USER", e.toString()));
    }

    // user not found or other error occurs
    return null;
}

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

/**
 * Adds a group of identities.//w w w .  j  av a  2  s  . c  om
 */
public void addGroup(IGroup group) throws EUsrGrpException {
    Group grp = (Group) group;

    if (grp == null) {
        return;
    }

    LDAPConnection ldapconn = null;

    try {
        String dn = "cn=" + LDAPUtil.escapeRDNValue(grp.getGroupID()) + "," + getGroupBaseDN();
        CMS.debug("dn: " + dn);

        LDAPAttributeSet attrs = new LDAPAttributeSet();
        String oc[] = { "top", "groupOfUniqueNames" };

        attrs.add(new LDAPAttribute("objectclass", oc));
        attrs.add(new LDAPAttribute("cn", group.getGroupID()));

        String description = group.getDescription();
        if (description != null) {
            CMS.debug("description: " + description);
            attrs.add(new LDAPAttribute("description", description));
        }

        Enumeration<String> e = grp.getMemberNames();

        if (e.hasMoreElements()) {
            LDAPAttribute attrMembers = new LDAPAttribute("uniquemember");

            while (e.hasMoreElements()) {
                String name = e.nextElement();

                String memberDN = "uid=" + LDAPUtil.escapeRDNValue(name) + "," + getUserBaseDN();
                CMS.debug("uniqueMember: " + memberDN);

                // DOES NOT SUPPORT NESTED GROUPS...
                attrMembers.addValue(memberDN);
            }
            attrs.add(attrMembers);
        }

        LDAPEntry entry = new LDAPEntry(dn, attrs);

        ldapconn = getConn();
        ldapconn.add(entry);

    } catch (LDAPException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_GROUP", e.toString()));
        throw LDAPExceptionConverter.toPKIException(e);

    } catch (ELdapException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_ADD_GROUP", e.toString()));
        throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ADD_GROUP_FAIL"));

    } finally {
        if (ldapconn != null)
            returnConn(ldapconn);
    }
}

From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java

/**
 * Modifies an existing group in the database.
 *
 * @param group   an existing group that has been modified in memory
 *///from w ww. j a v  a 2 s .c o  m
public void modifyGroup(IGroup group) throws EUsrGrpException {
    Group grp = (Group) group;

    if (grp == null) {
        return;
    }

    LDAPConnection ldapconn = null;

    try {
        String dn = "cn=" + LDAPUtil.escapeRDNValue(grp.getGroupID()) + "," + getGroupBaseDN();
        CMS.debug("dn: " + dn);

        LDAPModificationSet mod = new LDAPModificationSet();

        // update description
        String description = grp.getDescription();
        mod.add(LDAPModification.REPLACE, new LDAPAttribute("description", description));
        CMS.debug("description: " + description);

        Enumeration<String> e = grp.getMemberNames();

        // admin group cannot be empty
        if (grp.getName().equalsIgnoreCase(SUPER_CERT_ADMINS) && !e.hasMoreElements()) {
            throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_ILL_GRP_MOD"));
        }

        // update members
        LDAPAttribute attrMembers = new LDAPAttribute("uniquemember");
        while (e.hasMoreElements()) {
            String name = e.nextElement();

            String memberDN = "uid=" + LDAPUtil.escapeRDNValue(name) + "," + getUserBaseDN();
            CMS.debug("uniqueMember: " + memberDN);

            // DOES NOT SUPPORT NESTED GROUPS...
            attrMembers.addValue(memberDN);
        }
        mod.add(LDAPModification.REPLACE, attrMembers);

        ldapconn = getConn();
        ldapconn.modify(dn, mod);

    } catch (LDAPException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_MODIFY_GROUP", e.toString()));
        throw LDAPExceptionConverter.toPKIException(e);

    } catch (ELdapException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_USRGRP_MODIFY_GROUP", e.toString()));
        throw new EUsrGrpException(CMS.getUserMessage("CMS_USRGRP_MOD_GROUP_FAIL"));

    } finally {
        if (ldapconn != null)
            returnConn(ldapconn);
    }
}

From source file:com.gdo.servlet.RpcWrapper.java

public void doPost(StclContext stclContext, RpcArgs args) {
    try {//from w ww .ja v a 2 s.  c o m

        // gets stencil
        PStcl stcl = args.getStencilFromPath(stclContext);
        if (StencilUtils.isNull(stcl)) {
            if (!args.acceptNoStencil()) {
                fault(stclContext, SET_SERVICE, StencilUtils.getNullReason(stcl), args);
            }
            return;
        }

        // do set service for each value
        Enumeration<String> e = (Enumeration<String>) stclContext.getRequest().getParameterNames();
        while (e.hasMoreElements()) {
            String param = e.nextElement();
            if (StringUtils.isNotBlank(param) && param.length() > 2) {
                String type = param.substring(0, 1);
                String slot = param.substring(2);

                // sets string value
                if ("s".equals(type)) {
                    String value = args.getStringParameter(stclContext, param);
                    if (StringUtils.isEmpty(value)) {
                        stcl.setString(stclContext, slot, "");
                    } else {
                        stcl.setString(stclContext, slot, value);
                    }
                    continue;
                }

                // sets integer value
                if ("i".equals(type)) {
                    String str = stclContext.getRequest().getParameter(param);
                    if (StringUtils.isBlank(str)) {
                        stcl.setInt(stclContext, slot, 0);
                    } else {
                        stcl.setInt(stclContext, slot, Integer.parseInt(str));
                    }
                    continue;
                }

                // sets boolean value
                if ("b".equals(type)) {
                    String str = stclContext.getRequest().getParameter(param);
                    if (StringUtils.isBlank(str)) {
                        stcl.setBoolean(stclContext, slot, false);
                    } else {
                        stcl.setBoolean(stclContext, slot, ConverterHelper.parseBoolean(str));
                    }
                    continue;
                }

                // plugs value (value is path)
                if ("p".equals(type)) {
                    String path = stclContext.getRequest().getParameter(param);
                    if (StringUtils.isNotBlank(path)) {
                        PStcl toBePlugged = stcl.getStencil(stclContext, path);
                        stcl.plug(stclContext, toBePlugged, slot);
                    } else {
                        stcl.clearSlot(stclContext, slot);
                    }
                }
            }
        }

        // performs command after set/mset RPC calls
        stcl.afterRPCSet(stclContext);

    } catch (Exception e) {
        logError(stclContext, e.toString());
        fault(stclContext, FACET_SERVICE, e, null);
        return;
    }
}

From source file:com.netscape.cms.servlet.cert.DoRevoke.java

/**
 * Process cert status change request// w  w w.  j a v  a  2 s .  c o m
 * <P>
 *
 * (Certificate Request - either an "agent" cert status change request, or an "EE" cert status change request)
 * <P>
 *
 * (Certificate Request Processed - either an "agent" cert status change request, or an "EE" cert status change
 * request)
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when a cert status change request (e. g. -
 * "revocation") is made (before approval process)
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a certificate status is
 * changed (revoked, expired, on-hold, off-hold)
 * </ul>
 *
 * @param argSet CMS template parameters
 * @param header argument block
 * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
 *            2 - CA key compromised; should not be used, 3 - Affiliation changed,
 *            4 - Certificate superceded, 5 - Cessation of operation, or
 *            6 - Certificate is on hold)
 * @param invalidityDate certificate validity date
 * @param initiative string containing the audit format
 * @param req HTTP servlet request
 * @param resp HTTP servlet response
 * @param verifiedRecordCount number of verified records
 * @param revokeAll string containing information on all of the
 *            certificates to be revoked
 * @param totalRecordCount total number of records (verified and unverified)
 * @param eeSerialNumber BigInteger containing the end-entity certificate
 *            serial number
 * @param eeSubjectDN string containing the end-entity certificate subject
 *            distinguished name (DN)
 * @param comments string containing certificate comments
 * @param locale the system locale
 * @exception EBaseException an error has occurred
 */
private void process(CMSTemplateParams argSet, IArgBlock header, int reason, Date invalidityDate,
        String initiative, HttpServletRequest req, HttpServletResponse resp, int verifiedRecordCount,
        String revokeAll, int totalRecordCount, BigInteger eeSerialNumber, String eeSubjectDN, String comments,
        Locale locale) throws EBaseException {

    CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber);
    long startTime = CMS.getCurrentDate().getTime();

    RevocationProcessor processor = new RevocationProcessor(servletConfig.getServletName(), getLocale(req));

    processor.setStartTime(startTime);
    processor.setInitiative(initiative);
    processor.setSerialNumber(eeSerialNumber == null ? null : new CertId(eeSerialNumber));

    RevocationReason revReason = RevocationReason.fromInt(reason);
    processor.setRevocationReason(revReason);
    processor.setRequestType(
            processor.getRevocationReason() == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD
                    : RevocationProcessor.REVOKE);

    processor.setInvalidityDate(invalidityDate);
    processor.setComments(comments);

    Hashtable<BigInteger, Long> nonceMap = new Hashtable<BigInteger, Long>();
    X509Certificate clientCert = getSSLClientCertificate(req);

    if (mAuthority instanceof ICertificateAuthority) {
        processor.setAuthority(certAuthority);

        if (certAuthority.noncesEnabled()) {
            String nonces = req.getParameter("nonce");
            if (nonces == null) {
                throw new ForbiddenException("Missing nonce.");
            }

            // parse serial numbers and nonces
            for (String s : nonces.split(",")) {
                String[] elements = s.split(":");
                BigInteger serialNumber = new BigInteger(elements[0].trim());
                Long nonce = new Long(elements[1].trim());
                nonceMap.put(serialNumber, nonce);
            }
        }
    }

    try {
        processor.createCRLExtension();

        if (mAuthority instanceof ICertificateAuthority) {

            Enumeration<ICertRecord> e = mCertDB.searchCertificates(revokeAll, totalRecordCount, mTimeLimits);

            while (e != null && e.hasMoreElements()) {
                ICertRecord targetRecord = e.nextElement();
                X509CertImpl targetCert = targetRecord.getCertificate();

                // Verify end-entity cert is not revoked.
                // TODO: This should be checked during authentication.
                if (eeSerialNumber != null && eeSerialNumber.equals(targetCert.getSerialNumber())
                        && targetRecord.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1",
                            targetRecord.getSerialNumber().toString(16)));

                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

                IArgBlock rarg = CMS.createArgBlock();
                rarg.addStringValue("serialNumber", targetCert.getSerialNumber().toString(16));

                try {
                    if (mAuthority instanceof ICertificateAuthority && certAuthority.noncesEnabled()
                            && !processor.isMemberOfSubsystemGroup(clientCert)) {
                        // validate nonce for each certificate
                        Long nonce = nonceMap.get(targetRecord.getSerialNumber());
                        processor.validateNonce(req, "cert-revoke", targetRecord.getSerialNumber(), nonce);
                    }

                    processor.validateCertificateToRevoke(eeSubjectDN, targetRecord, false);
                    processor.addCertificateToRevoke(targetCert);
                    rarg.addStringValue("error", null);

                } catch (PKIException ex) {
                    rarg.addStringValue("error", ex.getMessage());
                }

                argSet.addRepeatRecord(rarg);
            }

        } else if (mAuthority instanceof IRegistrationAuthority) {
            String reqIdStr = req.getParameter("requestId");
            Collection<CertId> certSerialNumbers = new ArrayList<CertId>();

            if (revokeAll != null && revokeAll.length() > 0) {
                for (int i = revokeAll.indexOf('='); i > -1; i = revokeAll.indexOf('=', i)) {
                    i++;
                    // skip spaces
                    while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
                        i++;
                    }
                    // xxxx decimal serial number?
                    String legalDigits = "0123456789";
                    int j = i;

                    // find legal digits
                    while (j < revokeAll.length() && legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
                        j++;
                    }
                    if (j > i) {
                        certSerialNumbers.add(new CertId(revokeAll.substring(i, j)));
                    }
                }
            }

            if (reqIdStr != null && reqIdStr.length() > 0 && certSerialNumbers.size() > 0) {
                IRequest certReq = mRequestQueue.findRequest(new RequestId(reqIdStr));
                X509CertImpl[] certs = certReq.getExtDataInCertArray(IRequest.OLD_CERTS);
                boolean authorized = false;

                for (int i = 0; i < certs.length; i++) {
                    boolean addToList = false;

                    for (CertId certSerialNumber : certSerialNumbers) {
                        //xxxxx serial number in decimal?
                        if (certs[i].getSerialNumber().equals(certSerialNumber.toBigInteger())
                                && eeSubjectDN != null
                                && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) {
                            addToList = true;
                            break;
                        }
                    }

                    if (eeSerialNumber != null && eeSerialNumber.equals(certs[i].getSerialNumber())) {
                        authorized = true;
                    }

                    if (addToList) {
                        IArgBlock rarg = CMS.createArgBlock();

                        rarg.addStringValue("serialNumber", certs[i].getSerialNumber().toString(16));

                        processor.addCertificateToRevoke(certs[i]);

                        rarg.addStringValue("error", null);
                        argSet.addRepeatRecord(rarg);
                    }
                }

                if (!authorized) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT"));
                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

            } else {
                String b64eCert = req.getParameter("b64eCertificate");

                if (b64eCert != null) {
                    //  BASE64Decoder decoder = new BASE64Decoder();
                    //  byte[] certBytes = decoder.decodeBuffer(b64eCert);
                    byte[] certBytes = Utils.base64decode(b64eCert);
                    X509CertImpl cert = new X509CertImpl(certBytes);
                    IArgBlock rarg = CMS.createArgBlock();

                    rarg.addStringValue("serialNumber", cert.getSerialNumber().toString(16));

                    processor.addCertificateToRevoke(cert);

                    rarg.addStringValue("error", null);
                    argSet.addRepeatRecord(rarg);
                }
            }
        }

        int count = processor.getCertificates().size();
        if (count == 0) {
            processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
            throw new ECMSGWException(CMS.getLogMessage("CMSGW_REVOCATION_ERROR_CERT_NOT_FOUND"));
        }

        header.addIntegerValue("totalRecordCount", count);

        processor.createRevocationRequest();

        processor.auditChangeRequest(ILogger.SUCCESS);

    } catch (ForbiddenException e) {
        throw new EAuthzException(CMS.getUserMessage(locale, "CMS_AUTHORIZATION_ERROR"));

    } catch (CertificateException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        // TODO: throw exception or return?
        // throw new EBaseException(e.getMessage());
        return;

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        throw e;

    } catch (IOException e) {
        processor.log(ILogger.LL_FAILURE,
                CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
        processor.auditChangeRequest(ILogger.FAILURE);

        throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED"));
    }

    // change audit processing from "REQUEST" to "REQUEST_PROCESSED"
    // to distinguish which type of signed audit log message to save
    // as a failure outcome in case an exception occurs

    try {
        processor.processRevocationRequest();
        IRequest revReq = processor.getRequest();

        // retrieve the request status
        RequestStatus status = revReq.getRequestStatus();
        processor.setRequestStatus(status);

        String type = revReq.getRequestType();

        // The SVC_PENDING check has been added for the Cloned CA request
        // that is meant for the Master CA. From Clone's point of view
        // the request is complete

        if (status == RequestStatus.COMPLETE
                || status == RequestStatus.SVC_PENDING && type.equals(IRequest.CLA_CERT4CRL_REQUEST)) {

            header.addStringValue("revoked", "yes");

            Integer updateCRLResult = revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);

            if (updateCRLResult != null) {
                header.addStringValue("updateCRL", "yes");
                if (updateCRLResult.equals(IRequest.RES_SUCCESS)) {
                    header.addStringValue("updateCRLSuccess", "yes");
                } else {
                    header.addStringValue("updateCRLSuccess", "no");
                    String crlError = revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);

                    if (crlError != null)
                        header.addStringValue("updateCRLError", crlError);
                }

                // let known crl publishing status too.
                Integer publishCRLResult = revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);

                if (publishCRLResult != null) {
                    if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
                        header.addStringValue("publishCRLSuccess", "yes");
                    } else {
                        header.addStringValue("publishCRLSuccess", "no");
                        String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                        if (publError != null)
                            header.addStringValue("publishCRLError", publError);
                    }
                }
            }

            if (mAuthority instanceof ICertificateAuthority) {
                // let known update and publish status of all crls.
                Enumeration<ICRLIssuingPoint> otherCRLs = ((ICertificateAuthority) mAuthority)
                        .getCRLIssuingPoints();

                while (otherCRLs.hasMoreElements()) {
                    ICRLIssuingPoint crl = otherCRLs.nextElement();
                    String crlId = crl.getId();

                    if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
                        continue;

                    String updateStatusStr = crl.getCrlUpdateStatusStr();
                    Integer updateResult = revReq.getExtDataInInteger(updateStatusStr);

                    if (updateResult != null) {
                        if (updateResult.equals(IRequest.RES_SUCCESS)) {
                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER", updateStatusStr));
                            header.addStringValue(updateStatusStr, "yes");

                        } else {
                            String updateErrorStr = crl.getCrlUpdateErrorStr();

                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO", updateStatusStr));
                            header.addStringValue(updateStatusStr, "no");
                            String error = revReq.getExtDataInString(updateErrorStr);

                            if (error != null)
                                header.addStringValue(updateErrorStr, error);
                        }

                        String publishStatusStr = crl.getCrlPublishStatusStr();
                        Integer publishResult = revReq.getExtDataInInteger(publishStatusStr);

                        if (publishResult == null)
                            continue;

                        if (publishResult.equals(IRequest.RES_SUCCESS)) {
                            header.addStringValue(publishStatusStr, "yes");

                        } else {
                            String publishErrorStr = crl.getCrlPublishErrorStr();
                            header.addStringValue(publishStatusStr, "no");
                            String error = revReq.getExtDataInString(publishErrorStr);

                            if (error != null)
                                header.addStringValue(publishErrorStr, error);
                        }
                    }
                }
            }

            if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
                header.addStringValue("dirEnabled", "yes");
                Integer[] ldapPublishStatus = revReq.getExtDataInIntegerArray("ldapPublishStatus");
                int certsToUpdate = 0;
                int certsUpdated = 0;

                if (ldapPublishStatus != null) {
                    certsToUpdate = ldapPublishStatus.length;
                    for (int i = 0; i < certsToUpdate; i++) {
                        if (ldapPublishStatus[i] == IRequest.RES_SUCCESS) {
                            certsUpdated++;
                        }
                    }
                }

                header.addIntegerValue("certsUpdated", certsUpdated);
                header.addIntegerValue("certsToUpdate", certsToUpdate);

                // add crl publishing status.
                String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                if (publError != null) {
                    header.addStringValue("crlPublishError", publError);
                }

            } else {
                header.addStringValue("dirEnabled", "no");
            }

            header.addStringValue("error", null);

        } else {
            if (status == RequestStatus.PENDING || status == RequestStatus.REJECTED) {
                header.addStringValue("revoked", status.toString());
            } else {
                header.addStringValue("revoked", "no");
            }

            Vector<String> errors = revReq.getExtDataInStringVector(IRequest.ERRORS);
            if (errors != null) {
                StringBuilder errInfo = new StringBuilder();
                for (int i = 0; i < errors.size(); i++) {
                    errInfo.append(errors.elementAt(i));
                    errInfo.append("\n");
                }
                header.addStringValue("error", errInfo.toString());

            } else if (status == RequestStatus.PENDING) {
                header.addStringValue("error", "Request Pending");

            } else {
                header.addStringValue("error", null);
            }
        }

        processor.auditChangeRequestProcessed(ILogger.SUCCESS);

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequestProcessed(ILogger.FAILURE);

        throw e;
    }
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;/*w ww  .  j  a v a 2 s .c  om*/
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.wikipedia.nirvana.archive.ArchiveWithHeaders.java

public ArchiveWithHeaders(String text, int parseCount, boolean addToTop, String delimeter,
        Enumeration enumeration) {
    log.debug("ArchiveWithHeaders created, enumeration: " + enumeration.toString() + " top:" + addToTop);
    this.addToTop = addToTop;
    this.delimeter = delimeter;
    archivePartialText = "";
    this.enumeration = enumeration;
    parts = new ArrayList<Section>();
    if (parseCount >= 0)
        HOW_MANY_ITEMS_TO_PARSE = parseCount;

    init(text);/*ww w. j av  a  2s  .  co m*/
}

From source file:org.wikipedia.nirvana.archive.ArchiveWithHeaders.java

public ArchiveWithHeaders(int parseCount, boolean addToTop, String delimeter, Enumeration enumeration) {
    log.debug("ArchiveWithHeaders created, enumeration: " + enumeration.toString() + " top:" + addToTop);
    this.addToTop = addToTop;
    this.delimeter = delimeter;
    archivePartialText = "";
    this.enumeration = enumeration;
    if (parseCount >= 0)
        this.HOW_MANY_ITEMS_TO_PARSE = parseCount;
    parts = new ArrayList<Section>();
}

From source file:org.wikipedia.nirvana.archive.ArchiveWithHeaders.java

public ArchiveWithHeaders(String lines[], int parseCount, boolean addToTop, String delimeter,
        Enumeration enumeration) {
    log.debug("ArchiveWithHeaders created, enumeration: " + enumeration.toString() + " top:" + addToTop);
    this.addToTop = addToTop;
    this.delimeter = delimeter;
    archivePartialText = "";
    this.enumeration = enumeration;
    if (parseCount >= 0)
        this.HOW_MANY_ITEMS_TO_PARSE = parseCount;
    parts = new ArrayList<Section>();

    init(lines);//  w ww  .j  a  v a  2  s. c  om
}