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.liquidsite.core.content.User.java

/**
 * Creates an ASCII hash value for a string. The hash value
 * calculation is irreversible, and is calculated with the MD5
 * algorithm and encoded with base-64.//from  ww w.j  a va  2s .co  m
 *
 * @param input           the input string data
 *
 * @return the encoded hash value
 */
private String createHash(String input) {
    MessageDigest digest;
    byte bytes[];

    // Compute MD5 digest
    try {
        digest = MessageDigest.getInstance("MD5");
        digest.reset();
        digest.update(input.getBytes());
        bytes = digest.digest();
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage());
        return "";
    }

    // Base-64 encode digest
    return new String(Base64.encodeBase64(bytes));
}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

/**
 * @throws SystemException if jceks keystore is not available on {@link ProtectorImpl#getKeyStorePath}
 *//*from www.  j av a2  s . co  m*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = ProtectorImpl.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = ProtectorImpl.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        Set<String> keyEntryAliasesInKeyStore = new HashSet<>();

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance(KEY_DIGEST_TYPE);
        } catch (NoSuchAlgorithmException ex) {
            throw new EncryptionException(ex.getMessage(), ex);
        }

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            try {
                if (!keyStore.isKeyEntry(alias)) {
                    LOGGER.trace("Alias {} is not a key entry and shall be skipped", alias);
                    continue;
                }
                keyEntryAliasesInKeyStore.add(alias);
                Key key = keyStore.getKey(alias, KEY_PASSWORD);
                if (!(key instanceof SecretKey)) {
                    continue;
                }
                final SecretKey secretKey = (SecretKey) key;
                LOGGER.trace("Found secret key for alias {}", alias);
                aliasToSecretKeyHashMap.put(alias, secretKey);

                final String digest = Base64.encode(sha1.digest(key.getEncoded()));
                LOGGER.trace("Calculated digest {} for key alias {}", digest, key);
                digestToSecretKeyHashMap.put(digest, secretKey);

            } catch (UnrecoverableKeyException ex) {
                LOGGER.trace("Couldn't recover key {} from keystore, reason: {}",
                        new Object[] { alias, ex.getMessage() });
            }
        }
        LOGGER.trace("Found {} aliases in keystore identified as secret keys", aliasToSecretKeyHashMap.size());
        stream.close();

        // Initialize trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }

    randomNumberGenerator = new SecureRandom();
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public KeyStore getUserKeyStore(String storePassword) {

    try {/*from   ww  w . j a  v a  2  s.c  om*/
        NodeRef person = serviceRegistry.getPersonService().getPerson(user);

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

        KeyStore keystore = KeyStore.getInstance("pkcs12");

        // check to see if a keystore exists for this user
        NodeRef keystoreNode = counterSignService.getSignatureArtifact(person,
                CounterSignSignatureModel.ASSOC_SIGNERKEYSTORE);

        // if no keystore, create one, persist it and associate it with the user
        if (keystoreNode == null) {
            keystore = createUserKeyStore(person, storePassword);
        } else {
            // open the reader to the key and load it
            ContentReader keyReader = serviceRegistry.getContentService().getReader(keystoreNode,
                    ContentModel.PROP_CONTENT);
            keystore.load(keyReader.getContentInputStream(), storePassword.toCharArray());
        }

        // return the keystore
        return keystore;
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (java.security.cert.CertificateException ce) {
        throw new AlfrescoRuntimeException(ce.getMessage());
    } catch (NoSuchAlgorithmException nsaex) {
        throw new AlfrescoRuntimeException(nsaex.getMessage());
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (NoSuchProviderException nspex) {
        throw new AlfrescoRuntimeException(nspex.getMessage());
    }
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * build and validate cert path from end certificate.
 *
 * Note: the certpath return seems only include intermediate CA unless there is none in
 * which case the end cert is returned./*ww w .j  a  v  a2  s  . co m*/
 * @param endCert
 * @return CertPath  never null
 * @throws CertificatePathBuildingException
 */
private CertPath buildCertPath(X509Certificate endCert) throws CertificatePathBuildingException {

    CertPathBuilder cpb = null;
    try {
        cpb = CertPathBuilder.getInstance("PKIX");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificatePathBuildingException("Error building CertPathBuilder:" + e.getMessage(), e);
    }

    PKIXBuilderParameters params = CreatePKIXBuilderParameters(endCert);
    CertPathBuilderResult cpbResult;
    try {
        cpbResult = cpb.build(params);
    } catch (CertPathBuilderException e) {
        throw new CertificatePathBuildingException(e.getMessage(), e.getCause());
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificatePathBuildingException(e.getMessage(), e);
    }

    CertPath cp = cpbResult.getCertPath();

    return cp;
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

@Override
public boolean validateSignature(byte[] sig, byte[] hash) {
    String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM);
    String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER);

    boolean valid = false;

    try {//from   ww w.  ja  v  a2s.  co  m
        Signature validate = Signature.getInstance(alg, prov);
        validate.initVerify(getPublicKey());
        validate.update(hash);
        valid = validate.verify(sig);
    } catch (NoSuchProviderException nspe) {
        throw new AlfrescoRuntimeException("Provider: " + prov + " was not found: " + nspe.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException("Algorithm: " + alg + " is not available: " + nsae.getMessage());
    } catch (SignatureException se) {
        valid = false;
    } catch (InvalidKeyException ike) {
        valid = false;
    }

    return valid;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *///from www.ja v a 2 s.c  om
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

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

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

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

        KeyPair keyPair = keyGenerator.generateKeyPair();

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

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

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

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

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

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

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

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

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

            PKCS10CertificationRequest csr = builder.build(signGen);

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

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

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

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

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

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

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

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

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

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

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

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

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

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

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

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

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

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:com.vmware.identity.idm.server.clientcert.IdmCertificatePathValidator.java

/**
 * Validate the certificate path using a provided OCSP responder configuration.
 *
 * @param certPath      required/*from  w  w w  .j  a  va2s. co m*/
 * @param crlCollection
 * @param certStore     null possible cert store for PKIX param
 * @param altOCSP       null possible
 * @throws CertificateRevocationCheckException
 * @throws IdmCertificateRevokedException
 */
private void validateCertPath(CertPath certPath, Collection<Object> crlCollection, CertStore certStore,
        AlternativeOCSP altOCSP) throws CertificateRevocationCheckException, IdmCertificateRevokedException {

    setupOCSPOptions(certPath, altOCSP);
    PKIXParameters params = createPKIXParameters(crlCollection);

    if (null != certStore) {
        params.addCertStore(certStore);
    }

    CertPathValidator certPathValidator;
    try {
        certPathValidator = CertPathValidator.getInstance("PKIX");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateRevocationCheckException("Error getting PKIX validator instance:" + e.getMessage(),
                e);
    }

    try {
        String pkiParam = params.toString();
        logger.trace("**Certificate Path Validation Parameters trust anchors **\n"
                + params.getTrustAnchors().toString() + "\n");

        logger.trace("**Certificate Path Validation Parameters **\n" + pkiParam + "\n");

        CertPathValidatorResult result = certPathValidator.validate(certPath, params);

        logger.trace("**Certificate Path Validation Result **\n" + result.toString() + "\n");
    } catch (CertPathValidatorException e) {
        if (e.getReason() == CertPathValidatorException.BasicReason.REVOKED) {
            throw new IdmCertificateRevokedException("CRL shows certificate status as revoked");
        } else if (e.getReason() == CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS) {
            throw new CertRevocationStatusUnknownException(
                    "CRL checking could not determine certificate status.");
        }
        throw new CertificateRevocationCheckException("Certificate path validation failed:" + e.getMessage(),
                e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new CertificateRevocationCheckException(
                "Certificate validation parameters invalid, could not validate certificate path:"
                        + e.getMessage(),
                e);
    }

}

From source file:org.pentaho.runtime.test.network.impl.GatewayConnectivityTestImpl.java

@Override
public RuntimeTestResultEntry runTest() {

    if (StringUtils.isBlank(hostname)) {
        return new RuntimeTestResultEntryImpl(severityOfFalures,
                messageGetter.getMessage(CONNECT_TEST_HOST_BLANK_DESC),
                messageGetter.getMessage(CONNECT_TEST_HOST_BLANK_MESSAGE));
    } else {/*  w  w  w  .  j  a v  a2s.  c  om*/

        try {
            Integer portInt = Integer.parseInt(port);
            // Ignore ssl certificate issues if KETTLE_KNOX_IGNORE_SSL = true
            if (variables.getBooleanValueOfVariable("${KETTLE_KNOX_IGNORE_SSL}", false)) {
                SSLContext ctx = getTlsContext();
                initContextWithTrustAll(ctx);
                SSLContext.setDefault(ctx);
            }
            String userString = "";
            HttpClientContext context = null;
            HttpGet method = new HttpGet(uri.toString());
            HttpClient httpClient;

            if (StringUtils.isNotBlank(user)) {
                userString = user;
                httpClient = getHttpClient(user, password);
                context = HttpClientUtil.createPreemptiveBasicAuthentication(uri.getHost(), portInt, user,
                        password);
            } else {
                httpClient = getHttpClient();
            }

            HttpResponse httpResponse = context != null ? httpClient.execute(method, context)
                    : httpClient.execute(method);
            Integer returnCode = httpResponse.getStatusLine().getStatusCode();

            switch (returnCode) {
            case 200: {
                return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.INFO,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_SUCCESS_MESSAGE, uri.toString()));
            }
            case 404: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_DESC), messageGetter
                                .getMessage(GATEWAY_CONNECT_TEST_SERVICE_NOT_FOUND_MESSAGE, uri.toString()));
            }
            case 403: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_FORBIDDEN_DESC), messageGetter.getMessage(
                                GATEWAY_CONNECT_TEST_FORBIDDEN_MESSAGE, uri.toString(), userString));
            }
            case 401: {
                return new RuntimeTestResultEntryImpl(severityOfFalures,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_UNAUTHORIZED_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_UNAUTHORIZED_MESSAGE, uri.toString(),
                                userString));
            }
            default: {
                return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.WARNING,
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_DESC),
                        messageGetter.getMessage(GATEWAY_CONNECT_TEST_CONNECT_UNKNOWN_RETURN_CODE_MESSAGE,
                                userString, returnCode.toString(), uri.toString()));
            }
            }
        } catch (NoSuchAlgorithmException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXT_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXT_MESSAGE), e);
        } catch (SSLException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(GATEWAY_CONNECT_SSLEXCEPTION_DESC), messageGetter.getMessage(
                            GATEWAY_CONNECT_SSLEXCEPTION_MESSAGE, uri.toString(), e.getMessage()),
                    e);
        } catch (UnknownHostException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(CONNECT_TEST_UNKNOWN_HOSTNAME_DESC),
                    messageGetter.getMessage(CONNECT_TEST_UNKNOWN_HOSTNAME_MESSAGE, uri.getHost()), e);
        } catch (KeyManagementException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXTINIT_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_TLSCONTEXTINIT_MESSAGE), e);
        } catch (IOException e) {
            return new RuntimeTestResultEntryImpl(severityOfFalures,
                    messageGetter.getMessage(GATEWAY_CONNECT_EXECUTION_FAILED_DESC),
                    messageGetter.getMessage(GATEWAY_CONNECT_EXECUTION_FAILED_MESSAGE, uri.toString()), e);
        } catch (NumberFormatException e) {
            return new RuntimeTestResultEntryImpl(RuntimeTestEntrySeverity.FATAL,
                    messageGetter.getMessage(CONNECT_TEST_PORT_NUMBER_FORMAT_DESC),
                    messageGetter.getMessage(CONNECT_TEST_PORT_NUMBER_FORMAT_MESSAGE, port), e);
        }
    }
}

From source file:com.digitalgeneralists.assurance.model.compare.ComparisonEngine.java

private void determineDifferences(File source, File target, Scan scan, IFileComparor comparor,
        IAssuranceThreadPool threadPool, IScanOptions options, Collection<FileReference> exclusions,
        IProgressMonitor monitor) {//from  w ww .j  a v  a  2s. co m
    if (monitor != null) {
        StringBuffer message = new StringBuffer(512);
        monitor.publish(message.append("Comparing ").append(source.toString()).append(" to ")
                .append(target.toString()));
        message.setLength(0);
        message = null;
    }

    if ((source == null) && (target == null)) {
        StringBuffer message = new StringBuffer(512);
        logger.info(message.append(source).append(" and ").append(target).append(" are both null."));
        message.setLength(0);
        message = null;
    } else {
        // If the source file or target file is in the the global
        // ignore or exclusion list, just bypass it.
        // Checking both files in case one is null, in which case
        // we would have a mismatch.
        if (((!this.fileIsInGlobalIgnore(source, options)) && (!this.fileIsInGlobalIgnore(target, options)))
                && ((!this.fileIsInExclusions(source, exclusions))
                        && (!this.fileIsInExclusions(target, exclusions)))) {
            // Neither source or target is in the global ignore lists.

            // Only if both the source and target are not null.
            // NOTE: This logical condition isn't ideal. It works but
            // it is still not great in terms of readability.
            if ((source != null) && (target != null)) {
                if ((source.isDirectory()) && (!target.isDirectory())
                        || ((!source.isDirectory()) && (target.isDirectory()))) {
                    ComparisonResult result = new ComparisonResult(source, target,
                            AssuranceResultReason.FILE_DIRECTORY_MISMATCH, comparor);
                    scan.addResult(result);
                    result = null;
                    StringBuffer message = new StringBuffer(512);
                    logger.info(message.append(source).append(" does not match ").append(target));
                    message.setLength(0);
                    message = null;
                } else {
                    // Both files are either both simple files or both
                    // directories.

                    boolean sourceIsSymbolicLink = AssuranceUtils.checkIfFileIsSymbolicLink(source);
                    boolean targetIsSymbolicLink = AssuranceUtils.checkIfFileIsSymbolicLink(target);

                    if (sourceIsSymbolicLink && targetIsSymbolicLink) {
                        // Both files are symbolic links.  Only compare the paths.
                        if (!(source.getPath().equals(target.getPath()))) {
                            ComparisonResult result = new ComparisonResult(source, target,
                                    AssuranceResultReason.COMPARE_FAILED, comparor);
                            scan.addResult(result);
                            result = null;
                            StringBuffer message = new StringBuffer(512);
                            logger.info(message.append(source).append(" does not match ").append(target));
                            message.setLength(0);
                            message = null;
                        }
                    } else {
                        // Either file could be symbolic links.  Check for a mismatch.

                        if ((sourceIsSymbolicLink && !targetIsSymbolicLink)
                                || (!sourceIsSymbolicLink && targetIsSymbolicLink)) {
                            ComparisonResult result = new ComparisonResult(source, target,
                                    AssuranceResultReason.SYMBOLIC_LINK_MISMATCH, comparor);
                            scan.addResult(result);
                            result = null;
                            StringBuffer message = new StringBuffer(512);
                            logger.info(message.append(source).append(" does not match ").append(target));
                            message.setLength(0);
                            message = null;
                        }
                    }

                    if (!sourceIsSymbolicLink && !targetIsSymbolicLink) {
                        // Both files are not symbolic links.

                        if (source.isDirectory()) {
                            // The files are both directories.
                            for (File sourceFile : source.listFiles()) {
                                StringBuilder path = new StringBuilder(512);
                                File targetFile = new File(path.append(target.getPath()).append(File.separator)
                                        .append(sourceFile.getName()).toString());
                                path.setLength(0);
                                path = null;
                                // If the source file or target file is in the the global
                                // ignore or exclusion list, just bypass it.
                                // Checking both files in case one is null, in which case
                                // we would have a mismatch.
                                if (((!this.fileIsInGlobalIgnore(sourceFile, options))
                                        && (!this.fileIsInGlobalIgnore(targetFile, options)))
                                        && ((!this.fileIsInExclusions(sourceFile, exclusions))
                                                && (!this.fileIsInExclusions(targetFile, exclusions)))) {
                                    if (targetFile.exists()) {
                                        threadPool.submit(new ComparisonWorker(this, sourceFile, targetFile,
                                                scan, threadPool, options, exclusions, monitor));
                                    } else {
                                        ComparisonResult result = new ComparisonResult(sourceFile, targetFile,
                                                AssuranceResultReason.TARGET_DOES_NOT_EXIST, comparor);
                                        scan.addResult(result);
                                        result = null;
                                        StringBuffer message = new StringBuffer(512);
                                        logger.info(message.append(targetFile).append(" does not exist."));
                                        message.setLength(0);
                                        logger.info(message.append(sourceFile).append(" does not match ")
                                                .append(targetFile));
                                        message.setLength(0);
                                        message = null;
                                    }
                                }
                                targetFile = null;
                            }

                            this.identifyTargetItemsNotInSource(source, target, scan, comparor, options,
                                    exclusions, monitor);
                        } else {
                            // The files are both simple files.
                            try {
                                boolean includeTimestamps = true;
                                boolean includeAdvancedAttributes = true;
                                ScanDefinition scanDefinition = scan.getScanDef();
                                if (scanDefinition != null) {
                                    includeTimestamps = scanDefinition.getIncludeNonCreationTimestamps();
                                    includeAdvancedAttributes = scanDefinition.getIncludeAdvancedAttributes();
                                }
                                scanDefinition = null;

                                if (comparor.compare(source, target, includeTimestamps,
                                        includeAdvancedAttributes)) {
                                    StringBuffer message = new StringBuffer(512);
                                    logger.info(
                                            message.append(source).append(" is identical to ").append(target));
                                    message.setLength(0);
                                    message = null;
                                } else {
                                    ComparisonResult result = new ComparisonResult(source, target,
                                            AssuranceResultReason.COMPARE_FAILED, comparor);
                                    scan.addResult(result);
                                    result = null;
                                    StringBuffer message = new StringBuffer(512);
                                    logger.info(
                                            message.append(source).append(" does not match ").append(target));
                                    message.setLength(0);
                                    message = null;
                                }
                            } catch (NoSuchAlgorithmException e) {
                                ComparisonResult result = new ComparisonResult(source, target,
                                        AssuranceResultReason.UNDETERMINED, comparor);
                                result.setResolution(AssuranceResultResolution.PROCESSING_ERROR_ENCOUNTERED);
                                result.setResolutionError(e.getMessage());
                                scan.addResult(result);
                                result = null;
                                StringBuffer message = new StringBuffer(512);
                                logger.error(message.append("Error comparing ").append(source).append(" to ")
                                        .append(target), e);
                                message.setLength(0);
                                message = null;
                            } catch (IOException e) {
                                ComparisonResult result = new ComparisonResult(source, target,
                                        AssuranceResultReason.UNDETERMINED, comparor);
                                result.setResolution(AssuranceResultResolution.PROCESSING_ERROR_ENCOUNTERED);
                                result.setResolutionError(e.getMessage());
                                scan.addResult(result);
                                result = null;
                                StringBuffer message = new StringBuffer(512);
                                logger.error(message.append("Error comparing ").append(source).append(" to ")
                                        .append(target), e);
                                message.setLength(0);
                                message = null;
                            }
                        }
                    }
                }
            } else {
                ComparisonResult result = new ComparisonResult(source, target, AssuranceResultReason.FILE_NULL,
                        comparor);
                scan.addResult(result);
                result = null;
                StringBuffer message = new StringBuffer(512);
                logger.info(message.append(source).append(" does not match ").append(target));
                message.setLength(0);
                message = null;
            }
        }
    }
}

From source file:org.jini.commands.multicast.MulticastSender.java

/**
 * In this method all the execution of the specific Command takes place
 *///from ww w .ja  v  a 2  s. co  m
@Override
@SuppressWarnings("static-access")
public void executeCommand() {

    this.setJCLIOptions();
    String args[] = this.convertToArray();
    try {
        CommandLine jcCmd = this.jcParser.parse(this.jcOptions, args);
        // Read the -h option
        if (jcCmd.hasOption('h')) {
            // Print help 
            printHelp();
        }

        // Reaf the -l option 
        if (jcCmd.hasOption('l')) {
            // Set the flag
            logDatagramMessages = true;
        }

        if ((this.done == false) && (this.jcError == false)) {
            // Read the -i option. Defines the interval between 2 Multicasts
            if (jcCmd.hasOption("i")) {
                try {
                    int i = Integer.parseInt(jcCmd.getOptionValue("i").trim());
                    //Set the interval
                    this.setInterval(i);
                } catch (Exception e) {
                    this.setJcError(true);
                    this.addErrorMessages("Error : Option defined for -i is not a number");
                }
            }

            // Read the -p option. Defines the port
            if (jcCmd.hasOption("p")) {
                try {
                    int p = Integer.parseInt(jcCmd.getOptionValue("p").trim());
                    // Set port
                    this.setPort(p);
                } catch (Exception e) {
                    this.setJcError(true);
                    this.addErrorMessages("Error : Option defined for -p is not a number");
                }
            } else {
                this.setJcError(true);
                this.addErrorMessages("Error : Please define a Option defined for -p");

            }

            // Read -mcg option. MultiCast Group
            if (jcCmd.hasOption("mcg")) {
                if (jcCmd.getOptionValue("p").length() > 0) {
                    // Set the MultiCast Group
                    this.setMulticastGroup(jcCmd.getOptionValue("mcg").trim());
                } else {
                    this.setJcError(true);
                    this.addErrorMessages("Error : Please define a Option defined for -mcg");
                }
            } else {
                this.setJcError(true);
                this.addErrorMessages("Error : Please define a Option defined for -mcg");
            }

            // Read the -f option. Absolute Path to File
            if (jcCmd.hasOption("f")) {
                String fle = jcCmd.getOptionValue("f").trim();

                if (fle.length() > 0) {
                    if (this.isFileCanRead(fle)) {
                        // Set the File 
                        this.setFile(fle.trim());
                    } else {
                        this.setJcError(true);
                        this.addErrorMessages("Error : File does not exsist or is unreadable. " + fle);
                    }
                }
            } else {
                this.setJcError(true);
                this.addErrorMessages("Error : Please define a Option defined for -f");
            }

            if (this.jcError == false) {
                try {
                    // Start Multicast Sender
                    this.startMulticastSender();
                } catch (NoSuchAlgorithmException ex) {
                    this.setJcError(true);
                    this.addErrorMessages("Error : " + ex);
                }
            }
        }
    } catch (org.apache.commons.cli.ParseException ex) {
        this.setJcError(true);
        this.addErrorMessages("Error : " + ex.getMessage());
    }
}