Example usage for java.security.cert X509Certificate getSubjectDN

List of usage examples for java.security.cert X509Certificate getSubjectDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectDN.

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:org.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java

protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl,
        final OMElement cientAuthEl, final OMElement httpsProtocolsEl,
        final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    if (keyStoreEl != null) {
        String location = getValueOfElementWithLocalName(keyStoreEl, "Location");
        String type = getValueOfElementWithLocalName(keyStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password");
        String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword");

        FileInputStream fis = null;
        try {/*from  w  w  w . j  a v a 2s. c  om*/
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Identity Keystore from : " + location);
            }

            keyStore.load(fis, storePassword.toCharArray());

            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
            if (log.isInfoEnabled() && keymanagers != null) {
                for (KeyManager keymanager : keymanagers) {
                    if (keymanager instanceof X509KeyManager) {
                        X509KeyManager x509keymanager = (X509KeyManager) keymanager;
                        Enumeration<String> en = keyStore.aliases();
                        while (en.hasMoreElements()) {
                            String s = en.nextElement();
                            X509Certificate[] certs = x509keymanager.getCertificateChain(s);
                            if (certs == null)
                                continue;
                            for (X509Certificate cert : certs) {
                                log.debug(name + " Subject DN: " + cert.getSubjectDN());
                                log.debug(name + " Issuer DN: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreEl != null) {
        String location = getValueOfElementWithLocalName(trustStoreEl, "Location");
        String type = getValueOfElementWithLocalName(trustStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password");

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Trust Keystore from : " + location);
            }

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
    final String s = cientAuthEl != null ? cientAuthEl.getText() : null;
    final SSLClientAuth clientAuth;
    if ("optional".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.OPTIONAL;
    } else if ("require".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.REQUIRED;
    } else {
        clientAuth = null;
    }

    String[] httpsProtocols = null;
    final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null;
    if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) {
        String[] configuredValues = configuredHttpsProtocols.trim().split(",");
        List<String> protocolList = new ArrayList<String>(configuredValues.length);
        for (String protocol : configuredValues) {
            if (!protocol.trim().isEmpty()) {
                protocolList.add(protocol.trim());
            }
        }

        httpsProtocols = protocolList.toArray(new String[protocolList.size()]);
    }

    try {
        final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS";
        SSLContext sslContext = SSLContext.getInstance(sslProtocolValue);
        sslContext.init(keymanagers, trustManagers, null);

        ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null)
                ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager)
                : null;

        return new SSLContextDetails(sslContext, sslSetupHandler);
    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method./*ww  w  .j  ava  2s.com*/
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:org.globus.gsi.TrustedCertificates.java

public synchronized void reload(String locations) {
    if (locations == null) {
        return;/*  w w  w . jav  a 2 s .  com*/
    }

    this.changed = false;

    StringTokenizer tokens = new StringTokenizer(locations, ",");
    File caDir = null;

    Map newCertSubjectDNMap = new HashMap();
    Map newSigningDNMap = new HashMap();

    while (tokens.hasMoreTokens()) {
        caDir = new File(tokens.nextToken().toString().trim());

        if (!caDir.canRead()) {
            logger.debug("Cannot read: " + caDir.getAbsolutePath());
            continue;
        }

        String caCertLocation = "file:" + caDir.getAbsolutePath();
        //            String sigPolPattern = caCertLocation + "/*.signing_policy";
        //            if (!caDir.isDirectory()) {
        //                sigPolPattern = getPolicyFileName(caCertLocation);
        //            }

        try {
            ms_trustStore = Stores.getTrustStore(caCertLocation + "/" + Stores.getDefaultCAFilesPattern());

            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString()))
                    newCertSubjectDNMap.put(cert.getSubjectDN().toString(), cert);
            }
        } catch (Exception e) {
            logger.warn("Failed to create trust store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
        } catch (GeneralSecurityException e) {
            logger.warn("Failed to create signing_policy store", e);
        }

        try {
            ms_sigPolStore = Stores
                    .getSigningPolicyStore(caCertLocation + "/" + Stores.getDefaultSigningPolicyFilesPattern());
            Collection<? extends Certificate> caCerts = KeyStoreUtil.getTrustedCertificates(ms_trustStore,
                    new X509CertSelector());
            Iterator iter = caCerts.iterator();
            while (iter.hasNext()) {
                X509Certificate cert = (X509Certificate) iter.next();
                X500Principal principal = cert.getSubjectX500Principal();
                if (!newCertSubjectDNMap.containsKey(cert.getSubjectDN().toString())) {
                    continue;
                }
                SigningPolicy policy;
                try {
                    policy = ms_sigPolStore.getSigningPolicy(principal);
                } catch (Exception e) {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("Invalid signing policy for CA certificate; skipping");
                        logger.debug("Invalid signing policy for CA certificate; skipping", e);
                        invalidPolicies.add(principal);
                    }
                    continue;
                }
                if (policy != null) {
                    newSigningDNMap.put(CertificateUtil.toGlobusID(policy.getCASubjectDN()), policy);
                } else {
                    if (!invalidPolicies.contains(principal)) {
                        logger.warn("no signing policy for ca cert " + cert.getSubjectDN());
                        invalidPolicies.add(principal);
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("Failed to create signing policy store", e);
        }
    }

    this.changed = true;
    this.certSubjectDNMap = newCertSubjectDNMap;
    this.policyDNMap = newSigningDNMap;

    if (this.changed) {
        this.certList = null;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd,
        final String keyAlias, final String signAlg, final boolean withTag) {
    try {/*from ww  w .  ja  v a 2s .c o  m*/
        if (odlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("KeyStore does not contain alias {}", keyAlias);
        return null;
    } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        LOG.error("Failed to generate certificate request", e);
        return null;
    }
}

From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w w  w.j  a  va 2 s  . co m
        // KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        /*
        if (this.keystoreUrl != null) {
        KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
        if (LOG.isDebugEnabled()) {
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String)aliases.nextElement();
                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null) {
                    LOG.debug("Certificate chain '" + alias + "':");
                    for (int c = 0; c < certs.length; c++) {
                        if (certs[c] instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate)certs[c];
                            LOG.debug(" Certificate " + (c + 1) + ":");
                            LOG.debug("  Subject DN: " + cert.getSubjectDN());
                            LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                            LOG.debug("  Valid from: " + cert.getNotBefore() );
                            LOG.debug("  Valid until: " + cert.getNotAfter());
                            LOG.debug("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
            }
        }
        keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        */
        if (this.truststoreUrls != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrls, this.truststorePasswords);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(null, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.otterca.persistence.entity.X509CertificateEntity.java

/**
 * Cache values within certificate. They should never be set directly and
 * the actual values in the database should be created via triggers.
 * //from   www . j  a  v  a2 s.co  m
 * @param cert
 */
protected final void cacheAttributes(X509Certificate cert) throws CertificateEncodingException, IOException {
    serialNumber = cert.getSerialNumber();
    certificate = cert.getEncoded();
    subject = cert.getSubjectDN().getName();
    issuer = cert.getIssuerDN().getName();
    notBefore = cert.getNotBefore();
    notAfter = cert.getNotAfter();

    //name = x509CertUtil.getName(cert);
    //fingerprint = x509CertUtil.getFingerprint(cert);
    //certHash = x509CertUtil.getCertificateHash(cert);
    //iHash = x509CertUtil.getIHash(cert);
    //sHash = x509CertUtil.getSHash(cert);
    //akidHash = x509CertUtil.getAkidHash(cert);
    //skidHash = x509CertUtil.getSkidHash(cert);
}

From source file:org.apache.xml.security.keys.keyresolver.implementations.X509SKIResolver.java

/**
 * Method engineResolveX509Certificate/* w  ww. j  av  a2 s  .  com*/
 * @inheritDoc
 * @param element
 * @param BaseURI
 * @param storage
 *
 * @throws KeyResolverException
 */
public X509Certificate engineLookupResolveX509Certificate(Element element, String BaseURI,
        StorageResolver storage) throws KeyResolverException {
    if (log.isDebugEnabled()) {
        log.debug("Can I resolve " + element.getTagName() + "?");
    }
    if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
        if (log.isDebugEnabled()) {
            log.debug("I can't");
        }
        return null;
    }
    /** Field _x509childObject[] */
    XMLX509SKI x509childObject[] = null;

    Element x509childNodes[] = null;
    x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);

    if (!((x509childNodes != null) && (x509childNodes.length > 0))) {
        if (log.isDebugEnabled()) {
            log.debug("I can't");
        }
        return null;
    }
    try {
        if (storage == null) {
            Object exArgs[] = { Constants._TAG_X509SKI };
            KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs);

            if (log.isDebugEnabled()) {
                log.debug("", ex);
            }

            throw ex;
        }

        x509childObject = new XMLX509SKI[x509childNodes.length];

        for (int i = 0; i < x509childNodes.length; i++) {
            x509childObject[i] = new XMLX509SKI(x509childNodes[i], BaseURI);
        }

        Iterator<Certificate> storageIterator = storage.getIterator();
        while (storageIterator.hasNext()) {
            X509Certificate cert = (X509Certificate) storageIterator.next();
            XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert);

            for (int i = 0; i < x509childObject.length; i++) {
                if (certSKI.equals(x509childObject[i])) {
                    if (log.isDebugEnabled()) {
                        log.debug("Return PublicKey from " + cert.getSubjectDN().getName());
                    }

                    return cert;
                }
            }
        }
    } catch (XMLSecurityException ex) {
        throw new KeyResolverException("empty", ex);
    }

    return null;
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayService.java

private void createKeystore() {
    try {/*  w w  w . j  a v  a2s .  com*/
        sslKeystore.load(null, null);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        // Copy current certs into our keystore so we can use it...
        // TODO: don't actually do this...
        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            sslKeystore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    saveKeystore();
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ProcessContext context = processContext;

    ProcessSessionFactory sessionFactory;
    do {/*from   ww  w  .jav  a  2  s  .com*/
        sessionFactory = sessionFactoryHolder.get();
        if (sessionFactory == null) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException e) {
            }
        }
    } while (sessionFactory == null);

    final ProcessSession session = sessionFactory.createSession();
    FlowFile flowFile = null;
    String holdUuid = null;
    String foundSubject = null;
    try {
        final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE;
        if (n == 0 || !spaceAvailable.get()) {
            if (context.getAvailableRelationships().isEmpty()) {
                spaceAvailable.set(false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Received request from " + request.getRemoteHost()
                            + " but no space available; Indicating Service Unavailable");
                }
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            } else {
                spaceAvailable.set(true);
            }
        }
        response.setHeader("Content-Type", MediaType.TEXT_PLAIN);

        final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER));

        final X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        foundSubject = DEFAULT_FOUND_SUBJECT;
        if (certs != null && certs.length > 0) {
            for (final X509Certificate cert : certs) {
                foundSubject = cert.getSubjectDN().getName();
                if (authorizedPattern.matcher(foundSubject).matches()) {
                    break;
                } else {
                    logger.warn("Rejecting transfer attempt from " + foundSubject
                            + " because the DN is not authorized, host=" + request.getRemoteHost());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn");
                    return;
                }
            }
        }

        final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER);
        Integer protocolVersion = null;
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion);
            } catch (final NumberFormatException e) {
                // Value was invalid. Treat as if the header were missing.
            }
        }

        final boolean destinationIsLegacyNiFi = (protocolVersion == null);
        final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER));
        final String contentType = request.getContentType();

        final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream())
                : request.getInputStream();

        final InputStream in = (streamThrottler == null) ? unthrottled
                : streamThrottler.newThrottledInputStream(unthrottled);

        if (logger.isDebugEnabled()) {
            logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold
                    + ", content-type=" + contentType + ", gzip=" + contentGzipped);
        }

        final AtomicBoolean hasMoreData = new AtomicBoolean(false);
        final FlowFileUnpackager unpackager;
        if (APPLICATION_FLOW_FILE_V3.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV3();
        } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV2();
        } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV1();
        } else {
            unpackager = null;
        }

        final Set<FlowFile> flowFileSet = new HashSet<>();

        do {
            final long startNanos = System.nanoTime();
            final Map<String, String> attributes = new HashMap<>();
            flowFile = session.create();
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) {
                        if (unpackager == null) {
                            IOUtils.copy(in, bos);
                            hasMoreData.set(false);
                        } else {
                            attributes.putAll(unpackager.unpackageFlowFile(in, bos));

                            if (destinationIsLegacyNiFi) {
                                if (attributes.containsKey("nf.file.name")) {
                                    // for backward compatibility with old nifi...
                                    attributes.put(CoreAttributes.FILENAME.key(),
                                            attributes.remove("nf.file.name"));
                                }

                                if (attributes.containsKey("nf.file.path")) {
                                    attributes.put(CoreAttributes.PATH.key(),
                                            attributes.remove("nf.file.path"));
                                }
                            }

                            hasMoreData.set(unpackager.hasMoreData());
                        }
                    }
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            // put metadata on flowfile
            final String nameVal = request.getHeader(CoreAttributes.FILENAME.key());
            if (StringUtils.isNotBlank(nameVal)) {
                attributes.put(CoreAttributes.FILENAME.key(), nameVal);
            }

            // put arbitrary headers on flow file
            for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) {
                String headerName = headerEnum.nextElement();
                if (headerPattern != null && headerPattern.matcher(headerName).matches()) {
                    String headerValue = request.getHeader(headerName);
                    attributes.put(headerName, headerValue);
                }
            }

            String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key());
            if (sourceSystemFlowFileIdentifier != null) {
                sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier;

                // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's
                // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event
                attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString());
            }

            flowFile = session.putAllAttributes(flowFile, attributes);
            session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(),
                    sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis);
            flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host",
                    request.getRemoteHost());
            flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject);
            flowFileSet.add(flowFile);

            if (holdUuid == null) {
                holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key());
            }
        } while (hasMoreData.get());

        if (createHold) {
            String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid;

            if (flowFileMap.containsKey(uuid)) {
                uuid = UUID.randomUUID().toString();
            }

            final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet,
                    System.currentTimeMillis());
            FlowFileEntryTimeWrapper previousWrapper;
            do {
                previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper);
                if (previousWrapper != null) {
                    uuid = UUID.randomUUID().toString();
                }
            } while (previousWrapper != null);

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            final String ackUri = "/" + basePath + "/holds/" + uuid;
            response.addHeader(LOCATION_HEADER_NAME, ackUri);
            response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE);
            response.getOutputStream().write(ackUri.getBytes("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}",
                        new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(),
                                foundSubject, flowFileSet.size(), uuid });
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            logger.info(
                    "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}",
                    new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile });

            session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS);
            session.commit();
        }
    } catch (final Throwable t) {
        session.rollback();
        if (flowFile == null) {
            logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { request.getRemoteHost(), foundSubject, t });
        } else {
            logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { flowFile, request.getRemoteHost(), foundSubject, t });
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
    }
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from  w  w w  .ja  va  2  s  . co  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}