/*
(non-Javadoc)

@see net.rubyeye.xmemcached.MemcachedClient#cas(java.lang.String, int,
net.rubyeye.xmemcached.CASOperation, net.rubyeye.xmemcached.transcoders.Transcoder)
326750
public final <T> boolean cas(String key, final int exp, final CASOperation<T> operation,
      final Transcoder<T> transcoder)
      throws TimeoutException, InterruptedException, MemcachedException {
    key = this.preProcessKey(key);
    byte[] keyBytes = ByteUtils.getBytes(key);
    ByteUtils.checkKey(keyBytes);
    GetsResponse<T> result = this.gets0(key, keyBytes, transcoder);
    return this.cas0(key, exp, result, operation, transcoder, keyBytes, false);
  }
463505
def set_cas(key, value, cas, ttl=nil, options=nil)
      ttl ||= @options[:expires_in].to_i
      perform(:set, key, value, ttl, cas, options)
    end
1013868
@Override
	public void getNext(CAS cas) throws IOException, CollectionException {
		if(mCurrentIndex == 0) {
			logger.info("Reading collection {} ({} documents)", inputDirPath, mFiles.size());
			progressLoggerTimer.schedule(new TimerTask() {
				private long lastSize = 0;
				private long lastTop = System.currentTimeMillis();
				
				@Override
				public void run() {
					long top = System.currentTimeMillis();
					long size = currentFileByteSize;
					AbstractTermSuiteCollectionReader.logger.info("{}% - {} processed out of {} ({} Mb/s) - Processing file {} (doc. {} out of {})", 
							String.format("%.2f", ((float)currentFileByteSize*100)/totalFileByteSize),
							fr.univnantes.termsuite.utils.FileUtils.humanReadableByteCount(currentFileByteSize, true),
							fr.univnantes.termsuite.utils.FileUtils.humanReadableByteCount(totalFileByteSize, true),
							String.format("%.2f", 0.001*((float)size-lastSize)/((float)Math.max(1, top-lastTop))),
							mFiles.get(mCurrentIndex).getName(),
							mCurrentIndex,
							mFiles.size()
							);
					lastSize = size;
					lastTop = top;
				}
			}, 5000l, 5000l);
		}
		File file = mFiles.get(mCurrentIndex++);
		this.currentFileByteSize += file.length();
		
		logger.debug("Reading file ("+this.mCurrentIndex+"/"+this.mFiles.size()+") " + file.getAbsolutePath());
		fillCas(cas, file);
		if(!hasNext())
			this.lastFileRead();
	}
4279
public function get($key = null, $cache_cb = null, &$cas_token = null)
    {

        if (isset($this->cacheListing [$key])) {
            return parent::get($key, $cache_cb, $cas_token);
        }

        return false;
    }
1088981
@Override
	public String getCacheKeyForJwtSSOToken(Subject subject, String encodedjwt) {
		// TODO Auto-generated method stub
		if (encodedjwt != null) {
			return HashUtils.digest(encodedjwt);
		} else if (subject != null) {
			String jwtssotoken = getJwtSSOToken(subject);
			if (jwtssotoken != null) {
				return HashUtils.digest(jwtssotoken);
			}
		}

		return null;
	}
899311
@Override
	public byte[] serializeAttributes(final MemcachedBackupSession sessions, final ConcurrentMap<String, Object> attributes) {
		if (attributes == null) {
        	throw new NullPointerException();
        }

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
        	// This performs a deep serialization of the target instance.
            // It's serialized to a string as flexjson doesn't like writing to
            // an OutputStreamWriter: it throws the exception "Stepping back two steps is not supported".
            // See https://github.com/moresandeep/memcached-session-manager/commit/db2faaa0a846e16d65ac0b14819689c67bf92c68#commitcomment-512505
        	final String serResult = serializer.deepSerialize(attributes);
        	if (LOG.isDebugEnabled()) {
        	    LOG.debug("JSON Serialised object: " + serResult);
        	}
        	return serResult.getBytes(); // converts to bytes
        } catch (final Exception e) {
        	LOG.warn("Caught Exception deserializing JSON " + e);
        	throw new IllegalArgumentException();
        } finally {
        	close(bos);
        }
	}
930962
function parseCasResponse(casBody, logger, callback) {
  xml2js(casBody, {
    explicitRoot: false,
    tagNameProcessors: [stripPrefix]
  }, function(err, serviceResponse) {
    /* istanbul ignore if */
    if (err) {
      logger.error('Failed to parse CAS server response when trying to validate ticket.');
      logger.error(err);
      return callback(err, {
        message: 'Failed to parse CAS server response when trying to validate ticket.'
      });
    }

    if (!serviceResponse) {
      logger.error('Invalid CAS server response.');
      return callback(new Error('Invalid CAS server response, serviceResponse empty.'), {
        message: 'Invalid CAS server response, serviceResponse empty.'
      });
    }

    var success = serviceResponse.authenticationSuccess && serviceResponse.authenticationSuccess[0];

    if (!success) {
      logger.error('Receive response from CAS when validating ticket, but the validation is failed.');
      logger.error('Cas response:', serviceResponse);
      return callback(null, {});
    }

    var casResponse = {};
    for (var casProperty in success) {
      casResponse[casProperty] = success[casProperty][0];
    }

    return callback(null, casResponse);
  })
}
531564
def get_cas_client(service_url=None, request=None):
    
    # Handle CAS_SERVER_URL without protocol and hostname
    server_url = django_settings.CAS_SERVER_URL
    if server_url and request and server_url.startswith('/'):
        scheme = request.META.get("X-Forwarded-Proto", request.scheme)
        server_url = scheme + "://" + request.META['HTTP_HOST'] + server_url
    # assert server_url.startswith('http'), "settings.CAS_SERVER_URL invalid"

    if not django_settings.CAS_VERIFY_SSL_CERTIFICATE:
        warnings.warn(
            "`CAS_VERIFY_SSL_CERTIFICATE` is disabled, meaning that SSL certificates "
            "are not being verified by a certificate authority. This can expose your "
            "system to various attacks and should _never_ be disabled in a production "
            "environment."
        )

    return CASClient(
        service_url=service_url,
        version=django_settings.CAS_VERSION,
        server_url=server_url,
        extra_login_params=django_settings.CAS_EXTRA_LOGIN_PARAMS,
        renew=django_settings.CAS_RENEW,
        username_attribute=django_settings.CAS_USERNAME_ATTRIBUTE,
        proxy_callback=django_settings.CAS_PROXY_CALLBACK,
        verify_ssl_certificate=django_settings.CAS_VERIFY_SSL_CERTIFICATE
    )
856539
private Map<String, T> internalGet(long to, TimeUnit unit,
      Collection<Operation> timedoutOps) throws InterruptedException,
      ExecutionException {
    if (!latch.await(to, unit)) {
      for (Operation op : ops) {
        if (op.getState() != OperationState.COMPLETE) {
          MemcachedConnection.opTimedOut(op);
          timedoutOps.add(op);
        } else {
          MemcachedConnection.opSucceeded(op);
        }
      }
    }
    for (Operation op : ops) {
      if (op.isCancelled()) {
        throw new ExecutionException(new CancellationException("Cancelled"));
      }
      if (op.hasErrored()) {
        throw new ExecutionException(op.getException());
      }
    }
    Map<String, T> m = new HashMap<String, T>();
    for (Map.Entry<String, Future<T>> me : rvMap.entrySet()) {
      m.put(me.getKey(), me.getValue().get());
    }
    return m;
  }
189660
void get(
    char[] chars,
    int start,
    int length,
    boolean invert,
    MatchSpaceKey msg,
    EvalCache cache,
    Object contextValue,
    SearchResults result)
      throws MatchingException, BadMessageFormatMatchingException {
    if (tc.isEntryEnabled())
      tc.entry(this,cclass, "get", new Object[]{chars,new Integer(start),new Integer(length),
        new Boolean(invert),msg,cache,result});
    if (start == chars.length || chars[start] != MatchSpace.NONWILD_MARKER)
      super.get(chars, start, length, invert, msg, cache, contextValue, result);
    if (tc.isEntryEnabled())
      tc.exit(this,cclass, "get");
  }
1268674
private void serverHelloDone(ServerHelloDone mesg) throws IOException {
        if (debug != null && Debug.isOn("handshake")) {
            mesg.print(System.out);
        }
        /*
         * Always make sure the input has been digested before we
         * start emitting data, to ensure the hashes are correctly
         * computed for the Finished and CertificateVerify messages
         * which we send (here).
         */
        input.digestNow();

        /*
         * FIRST ... if requested, send an appropriate Certificate chain
         * to authenticate the client, and remember the associated private
         * key to sign the CertificateVerify message.
         */
        PrivateKey signingKey = null;

        if (certRequest != null) {
            X509ExtendedKeyManager km = sslContext.getX509KeyManager();

            ArrayList<String> keytypesTmp = new ArrayList<>(4);

            for (int i = 0; i < certRequest.types.length; i++) {
                String typeName;

                switch (certRequest.types[i]) {
                case CertificateRequest.cct_rsa_sign:
                    typeName = "RSA";
                    break;

                case CertificateRequest.cct_dss_sign:
                    typeName = "DSA";
                    break;

                case CertificateRequest.cct_ecdsa_sign:
                    // ignore if we do not have EC crypto available
                    typeName = JsseJce.isEcAvailable() ? "EC" : null;
                    break;

                // Fixed DH/ECDH client authentication not supported
                case CertificateRequest.cct_rsa_fixed_dh:
                case CertificateRequest.cct_dss_fixed_dh:
                case CertificateRequest.cct_rsa_fixed_ecdh:
                case CertificateRequest.cct_ecdsa_fixed_ecdh:
                // Any other values (currently not used in TLS)
                case CertificateRequest.cct_rsa_ephemeral_dh:
                case CertificateRequest.cct_dss_ephemeral_dh:
                default:
                    typeName = null;
                    break;
                }

                if ((typeName != null) && (!keytypesTmp.contains(typeName))) {
                    keytypesTmp.add(typeName);
                }
            }

            String alias = null;
            int keytypesTmpSize = keytypesTmp.size();
            if (keytypesTmpSize != 0) {
                String keytypes[] =
                        keytypesTmp.toArray(new String[keytypesTmpSize]);

                if (conn != null) {
                    alias = km.chooseClientAlias(keytypes,
                        certRequest.getAuthorities(), conn);
                } else {
                    alias = km.chooseEngineClientAlias(keytypes,
                        certRequest.getAuthorities(), engine);
                }
            }

            CertificateMsg m1 = null;
            if (alias != null) {
                X509Certificate[] certs = km.getCertificateChain(alias);
                if ((certs != null) && (certs.length != 0)) {
                    PublicKey publicKey = certs[0].getPublicKey();
                    // for EC, make sure we use a supported named curve
                    if (publicKey instanceof ECPublicKey) {
                        ECParameterSpec params =
                            ((ECPublicKey)publicKey).getParams();
                        int index =
                            SupportedEllipticCurvesExtension.getCurveIndex(
                                params);
                        if (!SupportedEllipticCurvesExtension.isSupported(
                                index)) {
                            publicKey = null;
                        }
                    }
                    if (publicKey != null) {
                        m1 = new CertificateMsg(certs);
                        signingKey = km.getPrivateKey(alias);
                        session.setLocalPrivateKey(signingKey);
                        session.setLocalCertificates(certs);
                    }
                }
            }
            if (m1 == null) {
                //
                // No appropriate cert was found ... report this to the
                // server.  For SSLv3, send the no_certificate alert;
                // TLS uses an empty cert chain instead.
                //
                if (protocolVersion.v >= ProtocolVersion.TLS10.v) {
                    m1 = new CertificateMsg(new X509Certificate [0]);
                } else {
                    warningSE(Alerts.alert_no_certificate);
                }
            }

            //
            // At last ... send any client certificate chain.
            //
            if (m1 != null) {
                if (debug != null && Debug.isOn("handshake")) {
                    m1.print(System.out);
                }
                m1.write(output);
            }
        }

        /*
         * SECOND ... send the client key exchange message.  The
         * procedure used is a function of the cipher suite selected;
         * one is always needed.
         */
        HandshakeMessage m2;

        switch (keyExchange) {

        case K_RSA:
        case K_RSA_EXPORT:
            if (serverKey == null) {
                throw new SSLProtocolException
                        ("Server did not send certificate message");
            }

            if (!(serverKey instanceof RSAPublicKey)) {
                throw new SSLProtocolException
                        ("Server certificate does not include an RSA key");
            }

            /*
             * For RSA key exchange, we randomly generate a new
             * pre-master secret and encrypt it with the server's
             * public key.  Then we save that pre-master secret
             * so that we can calculate the keying data later;
             * it's a performance speedup not to do that until
             * the client's waiting for the server response, but
             * more of a speedup for the D-H case.
             *
             * If the RSA_EXPORT scheme is active, when the public
             * key in the server certificate is less than or equal
             * to 512 bits in length, use the cert's public key,
             * otherwise, the ephemeral one.
             */
            PublicKey key;
            if (keyExchange == K_RSA) {
                key = serverKey;
            } else {    // K_RSA_EXPORT
                if (JsseJce.getRSAKeyLength(serverKey) <= 512) {
                    // extraneous ephemeralServerKey check done
                    // above in processMessage()
                    key = serverKey;
                } else {
                    if (ephemeralServerKey == null) {
                        throw new SSLProtocolException("Server did not send" +
                            " a RSA_EXPORT Server Key Exchange message");
                    }
                    key = ephemeralServerKey;
                }
            }

            m2 = new RSAClientKeyExchange(protocolVersion, maxProtocolVersion,
                                sslContext.getSecureRandom(), key);
            break;
        case K_DH_RSA:
        case K_DH_DSS:
            /*
             * For DH Key exchange, we only need to make sure the server
             * knows our public key, so we calculate the same pre-master
             * secret.
             *
             * For certs that had DH keys in them, we send an empty
             * handshake message (no key) ... we flag this case by
             * passing a null "dhPublic" value.
             *
             * Otherwise we send ephemeral DH keys, unsigned.
             */
            // if (useDH_RSA || useDH_DSS)
            m2 = new DHClientKeyExchange();
            break;
        case K_DHE_RSA:
        case K_DHE_DSS:
        case K_DH_ANON:
            if (dh == null) {
                throw new SSLProtocolException
                    ("Server did not send a DH Server Key Exchange message");
            }
            m2 = new DHClientKeyExchange(dh.getPublicKey());
            break;
        case K_ECDHE_RSA:
        case K_ECDHE_ECDSA:
        case K_ECDH_ANON:
            if (ecdh == null) {
                throw new SSLProtocolException
                    ("Server did not send a ECDH Server Key Exchange message");
            }
            m2 = new ECDHClientKeyExchange(ecdh.getPublicKey());
            break;
        case K_ECDH_RSA:
        case K_ECDH_ECDSA:
            if (serverKey == null) {
                throw new SSLProtocolException
                        ("Server did not send certificate message");
            }
            if (serverKey instanceof ECPublicKey == false) {
                throw new SSLProtocolException
                        ("Server certificate does not include an EC key");
            }
            ECParameterSpec params = ((ECPublicKey)serverKey).getParams();
            ecdh = new ECDHCrypt(params, sslContext.getSecureRandom());
            m2 = new ECDHClientKeyExchange(ecdh.getPublicKey());
            break;
        case K_KRB5:
        case K_KRB5_EXPORT:
            String hostname = getHostSE();
            if (hostname == null) {
                throw new IOException("Hostname is required" +
                                " to use Kerberos cipher suites");
            }
            KerberosClientKeyExchange kerberosMsg =
                new KerberosClientKeyExchange(
                    hostname, isLoopbackSE(), getAccSE(), protocolVersion,
                sslContext.getSecureRandom());
            // Record the principals involved in exchange
            session.setPeerPrincipal(kerberosMsg.getPeerPrincipal());
            session.setLocalPrincipal(kerberosMsg.getLocalPrincipal());
            m2 = kerberosMsg;
            break;
        default:
            // somethings very wrong
            throw new RuntimeException
                                ("Unsupported key exchange: " + keyExchange);
        }
        if (debug != null && Debug.isOn("handshake")) {
            m2.print(System.out);
        }
        m2.write(output);


        /*
         * THIRD, send a "change_cipher_spec" record followed by the
         * "Finished" message.  We flush the messages we've queued up, to
         * get concurrency between client and server.  The concurrency is
         * useful as we calculate the master secret, which is needed both
         * to compute the "Finished" message, and to compute the keys used
         * to protect all records following the change_cipher_spec.
         */

        output.doHashes();
        output.flush();

        /*
         * We deferred calculating the master secret and this connection's
         * keying data; we do it now.  Deferring this calculation is good
         * from a performance point of view, since it lets us do it during
         * some time that network delays and the server's own calculations
         * would otherwise cause to be "dead" in the critical path.
         */
        SecretKey preMasterSecret;
        switch (keyExchange) {
        case K_RSA:
        case K_RSA_EXPORT:
            preMasterSecret = ((RSAClientKeyExchange)m2).preMaster;
            break;
        case K_KRB5:
        case K_KRB5_EXPORT:
            byte[] secretBytes =
                ((KerberosClientKeyExchange)m2).getUnencryptedPreMasterSecret();
            preMasterSecret = new SecretKeySpec(secretBytes,
                "TlsPremasterSecret");
            break;
        case K_DHE_RSA:
        case K_DHE_DSS:
        case K_DH_ANON:
            preMasterSecret = dh.getAgreedSecret(serverDH, true);
            break;
        case K_ECDHE_RSA:
        case K_ECDHE_ECDSA:
        case K_ECDH_ANON:
            preMasterSecret = ecdh.getAgreedSecret(ephemeralServerKey);
            break;
        case K_ECDH_RSA:
        case K_ECDH_ECDSA:
            preMasterSecret = ecdh.getAgreedSecret(serverKey);
            break;
        default:
            throw new IOException("Internal error: unknown key exchange "
                + keyExchange);
        }

        calculateKeys(preMasterSecret, null);

        /*
         * FOURTH, if we sent a Certificate, we need to send a signed
         * CertificateVerify (unless the key in the client's certificate
         * was a Diffie-Hellman key).).
         *
         * This uses a hash of the previous handshake messages ... either
         * a nonfinal one (if the particular implementation supports it)
         * or else using the third element in the arrays of hashes being
         * computed.
         */
        if (signingKey != null) {
            CertificateVerify m3;
            try {
                SignatureAndHashAlgorithm preferableSignatureAlgorithm = null;
                if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                    preferableSignatureAlgorithm =
                        SignatureAndHashAlgorithm.getPreferableAlgorithm(
                            peerSupportedSignAlgs, signingKey.getAlgorithm(),
                            signingKey);

                    if (preferableSignatureAlgorithm == null) {
                        throw new SSLHandshakeException(
                            "No supported signature algorithm");
                    }

                    String hashAlg =
                        SignatureAndHashAlgorithm.getHashAlgorithmName(
                                preferableSignatureAlgorithm);
                    if (hashAlg == null || hashAlg.length() == 0) {
                        throw new SSLHandshakeException(
                                "No supported hash algorithm");
                    }

                    handshakeHash.setCertificateVerifyAlg(hashAlg);
                }

                m3 = new CertificateVerify(protocolVersion, handshakeHash,
                    signingKey, session.getMasterSecret(),
                    sslContext.getSecureRandom(),
                    preferableSignatureAlgorithm);
            } catch (GeneralSecurityException e) {
                fatalSE(Alerts.alert_handshake_failure,
                    "Error signing certificate verify", e);
                // NOTREACHED, make compiler happy
                m3 = null;
            }
            if (debug != null && Debug.isOn("handshake")) {
                m3.print(System.out);
            }
            m3.write(output);
            output.doHashes();
        } else {
            if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
                handshakeHash.setCertificateVerifyAlg(null);
            }
        }

        /*
         * OK, that's that!
         */
        sendChangeCipherAndFinish(false);
    }
1109372
public static MemcachedClient create(final PippoSettings settings) {
        String host = settings.getString(HOST, "localhost:11211");
        String prot = settings.getString(PROT, "BINARY");
        CommandFactory protocol;
        switch (prot) {
            case "BINARY":
                protocol = new BinaryCommandFactory();
                break;
            case "TEXT":
                protocol = new TextCommandFactory();
                break;
            default:
                protocol = new BinaryCommandFactory();
                break;
        }
        String user = settings.getString(USER, "");
        String pass = settings.getString(PASS, "");
        List<String> autM = settings.getStrings(AUTM);
        String[] mechanisms = autM.toArray(new String[autM.size()]);
        return create(host, protocol, user, pass, mechanisms);
    }
938097
protected boolean checkForSignIn() {
		 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		 if ((authentication != null) && authentication.isAuthenticated()) {
			 LOG.debug("Security context contains CAS authentication");
			 return true;
		} 
		
		return false;
	 }
197816
public final <T> boolean replace(String key, final int exp, final T value,
      final Transcoder<T> transcoder, final long timeout)
      throws TimeoutException, InterruptedException, MemcachedException {
    key = this.preProcessKey(key);
    byte[] keyBytes = this.checkStoreArguments(key, exp, value);
    return this.sendStoreCommand(
        this.commandFactory.createReplaceCommand(key, keyBytes, exp, value, false, transcoder),
        timeout);
  }
477932
void setTranscoderService( final TranscoderService transcoderService ) {
        _transcoderService = transcoderService;
        _backupSessionService = new BackupSessionService( transcoderService, _sessionBackupAsync, _sessionBackupTimeout,
                _backupThreadCount, _storage, _memcachedNodesManager, _statistics );
    }
1337637
@ShellMethod(key = "decrypt-value", value = "Encrypt a CAS property value/setting via Jasypt")
    public void decryptValue(
        @ShellOption(value = {"value"},
            help = "Value to encrypt") final String value,
        @ShellOption(value = {"alg"},
            help = "Algorithm to use to encrypt") final String alg,
        @ShellOption(value = {"provider"},
            help = "Security provider to use to encrypt") final String provider,
        @ShellOption(value = {"password"},
            help = "Password (encryption key) to encrypt") final String password,
        @ShellOption(value = {"iterations"},
            help = "Key obtention iterations to encrypt") final String iterations) {

        val cipher = new CasConfigurationJasyptCipherExecutor(this.environment);
        cipher.setAlgorithm(alg);
        cipher.setPassword(password);
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        cipher.setProviderName(provider);
        cipher.setKeyObtentionIterations(iterations);
        val encrypted = cipher.decryptValue(value);
        LOGGER.info("==== Decrypted Value ====\n{}", encrypted);

    }
448658
@Override
    public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException,
            NoSuchAlgorithmException, KeyStoreException {

        final SSLContext context = SSLContext.getInstance("TLS");

        String httpProtocols = System.getProperty("https.protocols");
        System.setProperty("https.protocols", "TLSv1");

        if (httpProtocols != null) {
            System.setProperty("https.protocols", httpProtocols);
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory
                .getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePassword.toCharArray());
        context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[] {};
                    }

                    @Override
                    public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) {

                    }

                    @Override
                    public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) {

                    }
                }
        }, new SecureRandom());

        return context;
    }