Example usage for java.security NoSuchAlgorithmException getMessage

List of usage examples for java.security NoSuchAlgorithmException getMessage

Introduction

In this page you can find the example usage for java.security NoSuchAlgorithmException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java

private static DefaultHttpClient getHttpClient(int iPort) {
    try {/*from  www  .j a va 2 s  . co m*/
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("https", iPort, socketFactory));

        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);
        DefaultHttpClient client = new DefaultHttpClient();

        return new DefaultHttpClient(mgr, client.getParams());
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}

From source file:org.isatools.isatab.export.sra.SraExportPipelineComponent.java

/**
 * Builds the SRA elements that are related to this ISATAB assay. It adds runs and an experiment to the respective
 * set.// w  w w .ja v  a 2s . c o m
 *
 * @return true if it could successfully build the exported items.
 */
protected boolean buildExportedAssay(Assay assay, SubmissionType.FILES xsubFiles, RunSetType xrunSet,
        ExperimentSetType xexperimentSet, SampleSetType xsampleSet) {

    String assayAcc = assay.getAcc();

    boolean doExport = true;
    //
    if (containsAnnotation(assay, "EXPORT")) {

        log.info("HAS EXPORT COMMENT IN ASSAY");

        String export = assay.getSingleAnnotationValue("comment:Export");

        log.info("export is " + export);
        if (export.equalsIgnoreCase("no")) {
            doExport = false;
        } else {
            doExport = true;
        }
        //            doExport = !(export != null && export.toLowerCase().contains("yes"));

    } else {
        log.info("NO EXPORT COMMENT FOUND");
    }

    log.info("Perform export? " + doExport);

    if (doExport) {

        // Now create an experiment for the input material and link it to the run

        // get Material associated to the assay and get its identifier
        Material material = assay.getMaterial();
        String materialAcc = material.getAcc();

        //create a new SRA Experiment and assign ISA Material name as SRA Experiment Title
        ExperimentType xexp = ExperimentType.Factory.newInstance();
        xexp.setAlias(materialAcc);
        xexp.setTITLE("Sequencing library derived from sample " + material.getName());

        xexp.setCenterName(centerName);
        xexp.setBrokerName(brokerName);

        PlatformType xplatform = buildExportedPlatform(assay);
        if (xplatform == null) {
            return false;
        }
        xexp.setPLATFORM(xplatform);

        Map<SequencingProperties, String> sequencingProperties = getSequencingInstrumentAndLayout(assay);

        xexp.setPROCESSING(buildExportedProcessing(assay, sequencingProperties));

        STUDYREF xstudyRef = STUDYREF.Factory.newInstance();
        xstudyRef.setRefname(assay.getStudy().getAcc());
        xexp.setSTUDYREF(xstudyRef);
        EXPERIMENTREF xexpRef = EXPERIMENTREF.Factory.newInstance();
        xexpRef.setRefname(materialAcc);

        DESIGN xdesign = DESIGN.Factory.newInstance();
        xdesign.setDESIGNDESCRIPTION("See study and sample descriptions for details");

        SAMPLEDESCRIPTOR xsampleRef = buildExportedAssaySample(assay, xsampleSet);
        if (xsampleRef == null) {
            return false;
        }

        xdesign.setSAMPLEDESCRIPTOR(xsampleRef);

        LIBRARYDESCRIPTOR xlib = buildExportedLibraryDescriptor(assay);
        if (xlib == null) {
            return false;
        }
        xdesign.setLIBRARYDESCRIPTOR(xlib);

        SpotDescriptorType xspotd = buildExportedSpotDescriptor(assay, sequencingProperties);
        if (xspotd == null) {
            return false;
        }

        xdesign.setSPOTDESCRIPTOR(xspotd);

        xexp.setDESIGN(xdesign);

        Map<String, String> fileToMD5 = new HashMap<String, String>();

        // For each file, builds one run, with one data block and one file
        // TODO: We should introduce something like "Run Name", so that multiple files associated to a single run can be
        // specified
        //
        for (AssayResult ar : ProcessingUtils.findAssayResultsFromAssay(assay)) {
            Data data = ar.getData();
            String url = StringUtils.trimToNull(data.getUrl());

            Study study = ar.getStudy();

            if (url == null) {
                String msg = MessageFormat.format(
                        "The assay file of type {0} / {1} for study {2} has a data file node without file name, ignoring",
                        assay.getMeasurement().getName(), assay.getTechnologyName(), assay.getStudy().getAcc());
                nonRepeatedMessages.add(msg + ". Data node is " + data.getName());
                log.trace(msg);
                return false;
            }

            FILE.Filetype.Enum xfileType = null;
            String fileType = StringUtils.trimToNull(data.getSingleAnnotationValue("comment:SRA File Type"));
            if (fileType == null) {
                // Let's try to get it from the file extension
                //
                fileType = StringUtils.trimToNull(FilenameUtils.getExtension(url));
                if (fileType != null) {
                    xfileType = FILE.Filetype.Enum.forString(fileType.toLowerCase());
                }

                if (xfileType == null) {
                    String msg = MessageFormat.format(
                            "The assay file of type {0} / {1} for study {2} has a data file node without the annotation "
                                    + "'SRA file type' and I cannot compute the file type from the file name, ignoring the assay",
                            assay.getMeasurement().getName(), assay.getTechnologyName(),
                            assay.getStudy().getAcc());
                    nonRepeatedMessages.add(msg);
                    log.trace(msg + ". Data node is " + data.getName());
                    return false;
                }
            }

            if (xfileType == null) {
                // fileType is certainly non null at this point, cause it was explicitly provided and so we
                // have to process it
                //
                xfileType = FILE.Filetype.Enum.forString(fileType.toLowerCase());

                if (xfileType == null) {
                    String msg = MessageFormat.format(
                            "The assay file of type {0} / {1} for study {2} has a bad 'SRA File Type' annotation: '"
                                    + fileType + "'" + ", ignoring the assay",
                            assay.getMeasurement().getName(), assay.getTechnologyName(),
                            assay.getStudy().getAcc());
                    nonRepeatedMessages.add(msg);
                    log.trace(msg + ". Data node is " + data.getName());
                    return false;
                }
            }

            RunType xrun = RunType.Factory.newInstance();
            xrun.setAlias(assayAcc);
            xrun.setCenterName(centerName);
            xrun.setBrokerName(brokerName);

            DATABLOCK dataBlock = DATABLOCK.Factory.newInstance();
            FILES xfiles = FILES.Factory.newInstance();
            FILE xfile = FILE.Factory.newInstance();
            xfile.setFiletype(xfileType);
            xfile.setFilename(url);

            xfile.setChecksumMethod(ChecksumMethod.MD_5);

            String md5;

            if (!fileToMD5.containsKey(url)) {

                try {
                    md5 = IOUtils.getMD5(new File(this.sourcePath + "/" + url));
                    fileToMD5.put(url, md5);
                } catch (NoSuchAlgorithmException e) {
                    throw new TabInternalErrorException(
                            "Problem while trying to compute the MD5 for '" + url + "': " + e.getMessage(), e);
                } catch (IOException e) {
                    throw new TabIOException(
                            "I/O problem while trying to compute the MD5 for '" + url + "': " + e.getMessage(),
                            e);

                }
            }

            xfile.setChecksum(fileToMD5.get(url));

            xfiles.addNewFILE();
            xfiles.setFILEArray(0, xfile);
            dataBlock.setFILES(xfiles);
            xrun.addNewDATABLOCK();
            xrun.setDATABLOCKArray(xrun.sizeOfDATABLOCKArray() - 1, dataBlock);

            addExportedSubmissionFile(xsubFiles, url);
            // TODO: remove, it's deprecated now xrun.setTotalDataBlocks ( BigInteger.ONE );
            xrun.setEXPERIMENTREF(xexpRef);

            xrunSet.addNewRUN();
            xrunSet.setRUNArray(xrunSet.sizeOfRUNArray() - 1, xrun);
        }

        xexperimentSet.addNewEXPERIMENT();
        xexperimentSet.setEXPERIMENTArray(xexperimentSet.sizeOfEXPERIMENTArray() - 1, xexp);
    }

    return true;
}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * calculates hash for config file//w ww  . ja  v  a  2  s. c  om
 * @throws NullPointerException - if hash is null
 */
private void calculateFileConfigHash() throws NullPointerException {
    MessageDigest md = null;
    byte[] b = new byte[2048];
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Wrong algorithm provided while getting instance of MessageDigest: " + e.getMessage());
    }
    /**
     * try with resources. Autoclosing after exitting try block
     */
    try (InputStream is = Files.newInputStream(Paths.get(getConfigFile()));
            DigestInputStream dis = new DigestInputStream(is, md)) {
        while (dis.read(b) >= 0)
            ;
    } catch (IOException e) {
        LOG.error("Something has happenned reading file: " + e.getLocalizedMessage());
    }
    try {
        setFileConfigHash((new HexBinaryAdapter()).marshal(md.digest()));
    } catch (Exception e) {
        LOG.error("Something has happenned converting md5 sum to string: " + e.getLocalizedMessage());
    }
    if (null == getFileConfigHash())
        throw new NullPointerException("Hash for config file is null!");
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

/**
 * This will sign a SAMLR2 Identity artifact (assertion, request or response) represeted as a DOM tree
 * The signature will be inserted as the first child of the root element.
 *
 * @param doc/*from   w ww  . j a va  2 s.  c o m*/
 * @param id
 * @return
 */
protected Document sign(Document doc, String id) throws SamlR2SignatureException {
    try {

        Certificate cert = keyResolver.getCertificate();

        // Create a DOM XMLSignatureFactory that will be used to generate the
        // enveloped signature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        if (logger.isDebugEnabled())
            logger.debug("Creating XML DOM Digital Siganture (not signing yet!)");

        // Create a Reference to the enveloped document and
        // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
        // The URI must be the assertion ID

        List<Transform> transforms = new ArrayList<Transform>();
        transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // Magically, this solves assertion DS validation when embedded in a signed response :)
        transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null));

        Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms,
                null, null);

        // Use signature method based on key algorithm.
        String signatureMethod = SignatureMethod.DSA_SHA1;
        if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA"))
            signatureMethod = SignatureMethod.RSA_SHA1;

        logger.debug("Using signature method " + signatureMethod);

        // Create the SignedInfo, with the X509 Certificate
        /*
        SignedInfo si = fac.newSignedInfo
            (fac.newCanonicalizationMethod
                    (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                            (C14NMethodParameterSpec) null),
                    fac.newSignatureMethod(signatureMethod, null),
                    Collections.singletonList(ref));
         */
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));

        // Create a KeyInfo and add the Certificate to it
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        X509Data kv = kif.newX509Data(Collections.singletonList(cert));
        //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey());

        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
        javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ...");

        // Create a DOMSignContext and specify the DSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(),
                doc.getDocumentElement().getFirstChild());

        // Sign the assertion
        signature.sign(dsc);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ... DONE!");

        return doc;

    } catch (NoSuchAlgorithmException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (MarshalException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (SSOKeyResolverException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    }
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClient.java

public String rowHash(String keySpace, String columnFamily, String key) throws StorageClientException {
    MessageDigest hasher;/*from w  w  w.ja va2  s  .c  o m*/
    try {
        hasher = MessageDigest.getInstance(rowidHash);
    } catch (NoSuchAlgorithmException e1) {
        throw new StorageClientException("Unable to get hash algorithm " + e1.getMessage(), e1);
    }
    String keystring = keySpace + ":" + columnFamily + ":" + key;
    byte[] ridkey;
    try {
        ridkey = keystring.getBytes("UTF8");
    } catch (UnsupportedEncodingException e) {
        ridkey = keystring.getBytes();
    }
    return StorageClientUtils.encode(hasher.digest(ridkey));
}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * Generates the module id map used by the transport to encode/decode module names
 * using assigned module name ids.// w  w  w.java 2 s  . co  m
 *
 * @param deps
 *            The dependencies object
 *
 * @throws IOException
 */
protected void generateModuleIdMap(IDependencies deps) throws IOException {
    final String methodName = "generateModuleIdMap"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), methodName);
    }
    if (getModuleIdRegFunctionName() == null) {
        if (isTraceLogging) {
            log.finer("No module id list registration function - returning"); //$NON-NLS-1$
            log.exiting(AbstractHttpTransport.class.getName(), methodName);
        }
        return;
    }
    Map<String, String> names = new TreeMap<String, String>(); // Use TreeMap to get consistent ordering

    for (String name : deps.getDependencyNames()) {
        names.put(name, isTraceLogging ? deps.getURI(name).toString() : null);
    }
    for (String name : getSyntheticModuleNames()) {
        names.put(name, isTraceLogging ? "transport added" : null); //$NON-NLS-1$
    }
    if (isTraceLogging) {
        // Log the module name id list.  This information is useful when trying to determine
        // why different servers in the same cluster might be generating different list hashes.
        StringBuffer sb = new StringBuffer("Module ID list:\r\n"); //$NON-NLS-1$
        int i = 1;
        for (Map.Entry<String, String> entry : names.entrySet()) {
            sb.append(i++).append(": ").append(entry.getKey()).append(" - ").append(entry.getValue()) //$NON-NLS-1$//$NON-NLS-2$
                    .append("\r\n"); //$NON-NLS-1$
        }
        log.finer(sb.toString());
    }

    Map<String, Integer> idMap = new HashMap<String, Integer>(names.size());
    List<String> idList = new ArrayList<String>(names.size() + 1);
    idList.add(""); // slot 0 is unused //$NON-NLS-1$
    idList.addAll(names.keySet());
    for (int i = 1; i < idList.size(); i++) {
        idMap.put(idList.get(i), i);
    }

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
    } catch (NoSuchAlgorithmException e) {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, e.getMessage(), e);
        }
        throw new IOException(e);
    }
    moduleIdListHash = md.digest(idList.toString().getBytes("UTF-8")); //$NON-NLS-1$
    moduleIdMap = Collections.unmodifiableMap(idMap);
    moduleIdList = idList;

    if (log.isLoggable(Level.INFO)) {
        log.info("Module ID List hash = " + TypeUtil.byteArray2String(moduleIdListHash)); //$NON-NLS-1$
    }
    if (isTraceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), methodName);
    }
}

From source file:org.wso2.carbon.user.core.system.SystemUserRoleManager.java

public void addSystemUser(String userName, Object credential, String[] roleList) throws UserStoreException {

    Connection dbConnection = null;
    String password = (String) credential;
    try {/*from  w w  w .  ja  v a  2  s .  c  o  m*/
        dbConnection = DatabaseUtil.getDBConnection(dataSource);
        String sqlStmt1 = SystemJDBCConstants.ADD_USER_SQL;

        String saltValue = null;
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(UserCoreConstants.SHA_1_PRNG);
            byte[] bytes = new byte[16];
            //secureRandom is automatically seeded by calling nextBytes
            secureRandom.nextBytes(bytes);
            saltValue = Base64.encode(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1PRNG algorithm could not be found.");
        }

        password = this.preparePassword(password, saltValue);

        this.updateStringValuesToDatabase(dbConnection, sqlStmt1, userName, password, saltValue, false,
                new Date(), tenantId);

        // add user to role.
        updateSystemRoleListOfUser(userName, null, roleList);

        dbConnection.commit();
    } catch (Throwable e) {
        try {
            if (dbConnection != null) {
                dbConnection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error while rollbacking add system user operation", e1);
        }
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection);
    }
}

From source file:ch.cyberduck.core.s3.S3Path.java

/**
 * @param throttle Bandwidth throttle//from  w w w. j  a  v a  2 s.c o  m
 * @param listener Callback for bytes sent
 * @param status   Transfer status
 * @param object   File location
 * @throws IOException      I/O error
 * @throws ServiceException Service error
 */
private void uploadSingle(final BandwidthThrottle throttle, final StreamListener listener,
        final TransferStatus status, final StorageObject object) throws IOException, ServiceException {

    InputStream in = null;
    ResponseOutputStream<StorageObject> out = null;
    MessageDigest digest = null;
    if (!Preferences.instance().getBoolean("s3.upload.metadata.md5")) {
        // Content-MD5 not set. Need to verify ourselves instad of S3
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
        }
    }
    try {
        if (null == digest) {
            log.warn("MD5 calculation disabled");
            in = this.getLocal().getInputStream();
        } else {
            in = new DigestInputStream(this.getLocal().getInputStream(), digest);
        }
        out = this.write(object, status.getLength() - status.getCurrent(),
                Collections.<String, String>emptyMap());
        this.upload(out, in, throttle, listener, status);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    if (null != digest) {
        final StorageObject part = out.getResponse();
        this.getSession().message(MessageFormat
                .format(Locale.localizedString("Compute MD5 hash of {0}", "Status"), this.getName()));
        // Obtain locally-calculated MD5 hash.
        String hexMD5 = ServiceUtils.toHex(digest.digest());
        this.getSession().getClient().verifyExpectedAndActualETagValues(hexMD5, part);
    }
}

From source file:ch.cyberduck.core.s3.S3Path.java

private Future<MultipartPart> submitPart(final BandwidthThrottle throttle, final StreamListener listener,
        final TransferStatus status, final MultipartUpload multipart, final ExecutorService pool,
        final int partNumber, final long offset, final long length) throws ConnectionCanceledException {
    if (pool.isShutdown()) {
        throw new ConnectionCanceledException();
    }/*from   w w w.j  a v a  2  s  . c om*/
    log.info(String.format("Submit part %d to queue", partNumber));
    return pool.submit(new Callable<MultipartPart>() {
        @Override
        public MultipartPart call() throws IOException, ServiceException {
            final Map<String, String> requestParameters = new HashMap<String, String>();
            requestParameters.put("uploadId", multipart.getUploadId());
            requestParameters.put("partNumber", String.valueOf(partNumber));

            InputStream in = null;
            ResponseOutputStream<StorageObject> out = null;
            MessageDigest digest = null;
            try {
                if (!Preferences.instance().getBoolean("s3.upload.metadata.md5")) {
                    // Content-MD5 not set. Need to verify ourselves instad of S3
                    try {
                        digest = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException e) {
                        log.error(e.getMessage());
                    }
                }
                if (null == digest) {
                    log.warn("MD5 calculation disabled");
                    in = getLocal().getInputStream();
                } else {
                    in = new DigestInputStream(getLocal().getInputStream(), digest);
                }
                out = write(new StorageObject(getKey()), length, requestParameters);
                upload(out, in, throttle, listener, offset, length, status);
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
            final StorageObject part = out.getResponse();
            if (null != digest) {
                // Obtain locally-calculated MD5 hash
                String hexMD5 = ServiceUtils.toHex(digest.digest());
                getSession().getClient().verifyExpectedAndActualETagValues(hexMD5, part);
            }
            // Populate part with response data that is accessible via the object's metadata
            return new MultipartPart(partNumber, part.getLastModifiedDate(), part.getETag(),
                    part.getContentLength());
        }
    });
}

From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java

public KeyStore getTlsKeystore() throws KeyStoreException {
    if (isBlank(myTlsKeystoreLocation) || isTls() == false) {
        return null;
    }/*from   w  w w  .ja v a  2 s  . c o m*/
    if (myTlsKeystore != null) {
        return myTlsKeystore;
    }

    File jksFile = new File(myTlsKeystoreLocation);
    if (!jksFile.exists() || !jksFile.canRead()) {
        throw new KeyStoreException("File does not exist or can not be read: " + jksFile.getAbsolutePath());
    }

    char[] password = null;
    if (isNotBlank(myTlsKeystorePassword)) {
        password = myTlsKeystorePassword.toCharArray();
    }

    KeyStore keystore;
    try {
        keystore = KeystoreUtils.loadKeystore(jksFile, password);
    } catch (NoSuchAlgorithmException e) {
        ourLog.error("Failed to load keystore!", e);
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    } catch (CertificateException e) {
        ourLog.error("Failed to load keystore!", e);
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    } catch (IOException e) {
        ourLog.error("Failed to load keystore!", e);
        if (e.getCause() instanceof UnrecoverableKeyException) {
            throw new KeyStoreException("Keystore password appears to be incorrect");
        }
        throw new KeyStoreException("Failed to load keystore: " + e.getMessage());
    }

    if (this instanceof InboundConnection) {
        if (!KeystoreUtils.validateKeystoreForTlsReceiving(keystore)) {
            throw new KeyStoreException("Keystore contains no keys appropriate for receiving data");
        }
    } else if (this instanceof OutboundConnection) {
        if (!KeystoreUtils.validateKeystoreForTlsSending(keystore)) {
            throw new KeyStoreException("Keystore contains no keys appropriate for receiving data");
        }
    }

    myTlsKeystore = keystore;
    return myTlsKeystore;
}