text:
package org.apache.rampart.builder;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.EncryptedKeyToken;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.TrustException;
import org.apache.rampart.RampartConstants;
import org.apache.rampart.RampartException;
import org.apache.rampart.RampartMessageData;
import org.apache.rampart.policy.RampartPolicyData;
import org.apache.rampart.policy.model.KerberosConfig;
import org.apache.rampart.util.RampartUtil;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.secpolicy.model.AlgorithmSuite;
import org.apache.ws.secpolicy.model.IssuedToken;
import org.apache.ws.secpolicy.model.SecureConversationToken;
import org.apache.ws.secpolicy.model.SupportingToken;
import org.apache.ws.secpolicy.model.Token;
import org.apache.ws.secpolicy.model.X509Token;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.WSSecurityEngineResult;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.conversation.ConversationConstants;
import org.apache.ws.security.conversation.ConversationException;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.handler.WSHandlerResult;
import org.apache.ws.security.message.WSSecDKEncrypt;
import org.apache.ws.security.message.WSSecEncrypt;
import org.apache.ws.security.message.WSSecEncryptedKey;
import org.apache.ws.security.message.token.SecurityTokenReference;
import org.apache.ws.security.message.WSSecKerberosToken;
import org.apache.ws.secpolicy.model.KerberosToken;
import org.apache.ws.security.util.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

public class SymmetricBindingBuilder extends BindingBuilder {

    private static Log log = LogFactory.getLog(SymmetricBindingBuilder.class);
    private static Log tlog = LogFactory.getLog(RampartConstants.TIME_LOG);

    public void build(RampartMessageData rmd) throws RampartException {

        log.debug("SymmetricBindingBuilder build invoked");

        RampartPolicyData rpd = rmd.getPolicyData();
        if (rpd.isIncludeTimestamp()) {
            this.addTimestamp(rmd);
        }

        if (rmd.isInitiator()) {
            // Setup required tokens
            initializeTokens(rmd);
        }

        if (SPConstants.ENCRYPT_BEFORE_SIGNING.equals(rpd.getProtectionOrder())) {
            this.doEncryptBeforeSig(rmd);
        } else {
            this.doSignBeforeEncrypt(rmd);
        }

        log.debug("SymmetricBindingBuilder build invoked : DONE");

    }

    private void doEncryptBeforeSig(RampartMessageData rmd) throws RampartException {

        long t0 = 0, t1 = 0, t2 = 0;

        RampartPolicyData rpd = rmd.getPolicyData();

        Vector signatureValues = new Vector();

        if (tlog.isDebugEnabled()) {
            t0 = System.currentTimeMillis();
        }

        Token encryptionToken = rpd.getEncryptionToken();
        Vector encrParts = RampartUtil.getEncryptedParts(rmd);

        Vector sigParts = RampartUtil.getSignedParts(rmd);

        if (encryptionToken == null && encrParts.size() > 0) {
            throw new RampartException("encryptionTokenMissing");
        }

        if (encryptionToken != null && encrParts.size() > 0) {
            // The encryption token can be an IssuedToken or a
            // SecureConversationToken
            String tokenId = null;
            org.apache.rahas.Token tok = null;

            if (encryptionToken instanceof IssuedToken) {
                tokenId = rmd.getIssuedEncryptionTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("Issued EncryptionToken Id : " + tokenId);
                }
            } else if (encryptionToken instanceof SecureConversationToken) {
                tokenId = rmd.getSecConvTokenId();
                if (log.isDebugEnabled()) {
                    log.debug("SCT Id : " + tokenId);
                }
            } else if (encryptionToken instanceof X509Token) {
                if (rmd.isInitiator()) {
                    tokenId = setupEncryptedKey(rmd, encryptionToken);
                } else {
                    tokenId = getEncryptedKey(rmd);
                }
            } // TODO SAMLToken

            if (tokenId == null || tokenId.length() == 0) {
                throw new RampartException("noSecurityToken");
            }

            // Hack to handle reference id issues
            // TODO Need a better fix
            if (tokenId.startsWith("#")) {
                tokenId = tokenId.substring(1);
            }

            /*
             * Get hold of the token from the token storage
             */
            tok = this.getToken(rmd, tokenId);

            /*
             * Attach the token into the message based on token inclusion values
             */
            boolean attached = false;
            Element encrTokenElement = null;
            Element refList = null;
            WSSecDKEncrypt dkEncr = null;
            WSSecEncrypt encr = null;
            Element encrDKTokenElem = null;

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == encryptionToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == encryptionToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encryptionToken
                            .getInclusion())) {
                encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
                attached = true;
            } else if (encryptionToken instanceof X509Token && rmd.isInitiator()) {
                encrTokenElement = RampartUtil.appendChildToSecHeader(rmd, tok.getToken());
            }

            Document doc = rmd.getDocument();

            AlgorithmSuite algorithmSuite = rpd.getAlgorithmSuite();
            if (encryptionToken.isDerivedKeys()) {
                log.debug("Use drived keys");

                dkEncr = new WSSecDKEncrypt();

                if (attached && tok.getAttachedReference() != null) {

                    dkEncr.setExternalKey(tok.getSecret(),
                            (Element) doc.importNode((Element) tok.getAttachedReference(), true));

                } else if (tok.getUnattachedReference() != null) {
                    dkEncr.setExternalKey(tok.getSecret(),
                            (Element) doc.importNode((Element) tok.getUnattachedReference(), true));
                } else {
                    dkEncr.setExternalKey(tok.getSecret(), tok.getId());
                }
                try {
                    dkEncr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                    dkEncr.setDerivedKeyLength(algorithmSuite.getEncryptionDerivedKeyLength() / 8);
                    dkEncr.prepare(doc);
                    encrDKTokenElem = dkEncr.getdktElement();
                    RampartUtil.appendChildToSecHeader(rmd, encrDKTokenElem);

                    refList = dkEncr.encryptForExternalRef(null, encrParts);

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                log.debug("NO derived keys, use the shared secret");
                encr = new WSSecEncrypt();

                encr.setWsConfig(rmd.getConfig());
                encr.setEncKeyId(tokenId);
                RampartUtil.setEncryptionUser(rmd, encr);
                encr.setEphemeralKey(tok.getSecret());
                encr.setDocument(doc);
                encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                // SymmKey is already encrypted, no need to do it again
                encr.setEncryptSymmKey(false);
                if (!rmd.isInitiator() && tok instanceof EncryptedKeyToken) {
                    encr.setUseKeyIdentifier(true);
                    encr.setCustomReferenceValue(((EncryptedKeyToken) tok).getSHA1());
                    encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                }

                try {

                    encr.prepare(
                            doc,
                            RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                                    rmd.getCustomClassLoader()));
                    // Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }

            this.mainRefListElement = RampartUtil.appendChildToSecHeader(rmd, refList);

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }

            // Sometimes encryption token is not included in the the message
            if (encrTokenElement != null) {
                this.setInsertionLocation(encrTokenElement);
            } else if (timestampElement != null) {
                this.setInsertionLocation(timestampElement);
            }

            RampartUtil.handleEncryptedSignedHeaders(encrParts, sigParts, doc);

            HashMap sigSuppTokMap = null;
            HashMap endSuppTokMap = null;
            HashMap sgndEndSuppTokMap = null;
            HashMap sgndEncSuppTokMap = null;
            HashMap endEncSuppTokMap = null;
            HashMap sgndEndEncSuppTokMap = null;

            if (this.timestampElement != null) {
                sigParts.add(new WSEncryptionPart(RampartUtil
                        .addWsuIdToElement((OMElement) this.timestampElement)));
            }

            if (rmd.isInitiator()) {

                // Now add the supporting tokens
                SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
                sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

                SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
                endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

                SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
                sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

                SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
                sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

                SupportingToken endorsingEncryptedSuppTokens = rpd
                        .getEndorsingEncryptedSupportingTokens();
                endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

                SupportingToken sgndEndEncSuppTokens = rpd
                        .getSignedEndorsingEncryptedSupportingTokens();
                sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

                Vector supportingToks = rpd.getSupportingTokensList();
                for (int i = 0; i < supportingToks.size(); i++) {
                    this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
                }

                SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
                this.handleSupportingTokens(rmd, encryptedSupportingToks);

                // Setup signature parts
                sigParts = addSignatureParts(sigSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
                sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

            } else {
                addSignatureConfirmation(rmd, sigParts);
            }

            // Sign the message
            // We should use the same key in the case of EncryptBeforeSig
            if (sigParts.size() > 0) {
                signatureValues.add(this.doSymmSignature(rmd, encryptionToken, tok, sigParts));
                this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this
                        .getInsertionLocation());
            }

            if (rmd.isInitiator()) {

                endSuppTokMap.putAll(endEncSuppTokMap);
                // Do endorsed signatures
                Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);
                for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }

                sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
                // Do signed endorsing signatures
                Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
                for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                    signatureValues.add(iter.next());
                }
            }

            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
                tlog.debug("Encryption took :" + (t1 - t0) + ", Signature tool :" + (t2 - t1));
            }

            // Check for signature protection and encryption of UsernameToken
            if (rpd.isSignatureProtection() && this.mainSigId != null
                    || encryptedTokensIdList.size() > 0 && rmd.isInitiator()) {
                long t3 = 0, t4 = 0;
                if (tlog.isDebugEnabled()) {
                    t3 = System.currentTimeMillis();
                }
                log.debug("Signature protection");
                Vector secondEncrParts = new Vector();

                // Now encrypt the signature using the above token
                if (rpd.isSignatureProtection()) {
                    secondEncrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
                }

                if (rmd.isInitiator()) {
                    for (int i = 0; i < encryptedTokensIdList.size(); i++) {
                        secondEncrParts.add(new WSEncryptionPart((String) encryptedTokensIdList
                                .get(i), "Element"));
                    }
                }

                Element secondRefList = null;

                if (encryptionToken.isDerivedKeys()) {
                    try {
                        secondRefList = dkEncr.encryptForExternalRef(null, secondEncrParts);
                        RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, secondRefList);
                    } catch (WSSecurityException e) {
                        throw new RampartException("errorInDKEncr");
                    }
                } else {
                    try {
                        // Encrypt, get hold of the ref list and add it
                        secondRefList = encr.encryptForExternalRef(null, encrParts);
                        RampartUtil.insertSiblingAfter(rmd, encrTokenElement, secondRefList);
                    } catch (WSSecurityException e) {
                        throw new RampartException("errorInEncryption", e);
                    }
                }
                if (tlog.isDebugEnabled()) {
                    t4 = System.currentTimeMillis();
                    tlog.debug("Signature protection took :" + (t4 - t3));
                }
            }

        } else {
            throw new RampartException("encryptionTokenMissing");
        }
    }

    private void doSignBeforeEncrypt(RampartMessageData rmd) throws RampartException {

        long t0 = 0, t1 = 0, t2 = 0;

        RampartPolicyData rpd = rmd.getPolicyData();
        Document doc = rmd.getDocument();

        if (tlog.isDebugEnabled()) {
            t0 = System.currentTimeMillis();
        }
        Token sigToken = rpd.getSignatureToken();

        String encrTokId = null;
        String sigTokId = null;

        org.apache.rahas.Token encrTok = null;
        org.apache.rahas.Token sigTok = null;
        WSSecKerberosToken krbToken = null;

        Element sigTokElem = null;

        Vector signatureValues = new Vector();

        if (sigToken != null) {
            if (sigToken instanceof SecureConversationToken) {
                sigTokId = rmd.getSecConvTokenId();
            } else if (sigToken instanceof IssuedToken) {
                sigTokId = rmd.getIssuedSignatureTokenId();
            } else if (sigToken instanceof X509Token) {
                if (rmd.isInitiator()) {
                    sigTokId = setupEncryptedKey(rmd, sigToken);
                } else {
                    sigTokId = getEncryptedKey(rmd);
                }
            } else if (sigToken instanceof KerberosToken) {
                Date created = new Date();
                Date expires = new Date();
                // TODO make this lifetime configurable ???
                expires.setTime(System.currentTimeMillis() + 300000);
                krbToken = getKerberosTokenBuilder(rmd, sigToken);
                sigTokId = krbToken.getBSTTokenId();
                if (rmd.isInitiator()) {
                    sigTokElem = krbToken.getBinarySecurityTokenElement();
                }
                sigTok = new EncryptedKeyToken(sigTokId, created, expires);
                sigTok.setSecret(krbToken.getSessionKey().getEncoded());
            }
        } else {
            throw new RampartException("signatureTokenMissing");
        }

        if (sigTokId == null || sigTokId.length() == 0) {
            throw new RampartException("noSecurityToken");
        }

        if (!(sigToken instanceof KerberosToken)) {

            sigTok = this.getToken(rmd, sigTokId);

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == sigToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == sigToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == sigToken
                            .getInclusion())) {
                sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
            } else if ((rmd.isInitiator() && sigToken instanceof X509Token)
                    || sigToken instanceof SecureConversationToken) {
                sigTokElem = RampartUtil.appendChildToSecHeader(rmd, sigTok.getToken());
            }
        }

        if (sigTokElem != null) {
            // Set the insertion location
            this.setInsertionLocation(sigTokElem);
        }

        HashMap sigSuppTokMap = null;
        HashMap endSuppTokMap = null;
        HashMap sgndEndSuppTokMap = null;
        HashMap sgndEncSuppTokMap = null;
        HashMap endEncSuppTokMap = null;
        HashMap sgndEndEncSuppTokMap = null;

        Vector sigParts = RampartUtil.getSignedParts(rmd);

        if (this.timestampElement != null) {
            sigParts.add(new WSEncryptionPart(RampartUtil
                    .addWsuIdToElement((OMElement) this.timestampElement)));
        }

        if (rmd.isInitiator()) {
            // Now add the supporting tokens
            SupportingToken sgndSuppTokens = rpd.getSignedSupportingTokens();
            sigSuppTokMap = this.handleSupportingTokens(rmd, sgndSuppTokens);

            SupportingToken endSuppTokens = rpd.getEndorsingSupportingTokens();
            endSuppTokMap = this.handleSupportingTokens(rmd, endSuppTokens);

            SupportingToken sgndEndSuppTokens = rpd.getSignedEndorsingSupportingTokens();
            sgndEndSuppTokMap = this.handleSupportingTokens(rmd, sgndEndSuppTokens);

            SupportingToken sgndEncryptedSuppTokens = rpd.getSignedEncryptedSupportingTokens();
            sgndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEncryptedSuppTokens);

            SupportingToken endorsingEncryptedSuppTokens = rpd
                    .getEndorsingEncryptedSupportingTokens();
            endEncSuppTokMap = this.handleSupportingTokens(rmd, endorsingEncryptedSuppTokens);

            SupportingToken sgndEndEncSuppTokens = rpd
                    .getSignedEndorsingEncryptedSupportingTokens();
            sgndEndEncSuppTokMap = this.handleSupportingTokens(rmd, sgndEndEncSuppTokens);

            Vector supportingToks = rpd.getSupportingTokensList();
            for (int i = 0; i < supportingToks.size(); i++) {
                this.handleSupportingTokens(rmd, (SupportingToken) supportingToks.get(i));
            }

            SupportingToken encryptedSupportingToks = rpd.getEncryptedSupportingTokens();
            this.handleSupportingTokens(rmd, encryptedSupportingToks);

            // Setup signature parts
            sigParts = addSignatureParts(sigSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEncSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndSuppTokMap, sigParts);
            sigParts = addSignatureParts(sgndEndEncSuppTokMap, sigParts);

        } else {
            addSignatureConfirmation(rmd, sigParts);
        }

        if (sigParts.size() > 0) {
            if (sigToken instanceof KerberosToken) {
                krbToken.setParts(sigParts);
                try {
                    krbToken.signMessage();
                } catch (WSSecurityException e) {
                    throw new RampartException("errorInSignatureWithKerberosToken");
                }
                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd,
                        this.getInsertionLocation(), krbToken.getSignatureElement()));
                signatureValues.add(krbToken.getSignatureValue());
            } else {
                // Sign the message
                signatureValues.add(this.doSymmSignature(rmd, sigToken, sigTok, sigParts));
            }

            this.mainSigId = RampartUtil.addWsuIdToElement((OMElement) this.getInsertionLocation());

        }

        if (rmd.isInitiator()) {
            // Adding the endorsing encrypted supporting tokens to endorsing supporting tokens
            endSuppTokMap.putAll(endEncSuppTokMap);
            // Do endorsed signatures
            Vector endSigVals = this.doEndorsedSignatures(rmd, endSuppTokMap);

            for (Iterator iter = endSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }

            // Adding the signed endorsed encrypted tokens to signed endorsed supporting tokens
            sgndEndSuppTokMap.putAll(sgndEndEncSuppTokMap);
            // Do signed endorsing signatures
            Vector sigEndSigVals = this.doEndorsedSignatures(rmd, sgndEndSuppTokMap);
            for (Iterator iter = sigEndSigVals.iterator(); iter.hasNext();) {
                signatureValues.add(iter.next());
            }
        }

        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }

        // Encryption
        Token encrToken = rpd.getEncryptionToken();
        boolean isIssuedToken = false;
        if (encrToken instanceof IssuedToken) {
            isIssuedToken = true;
        }
        Element encrTokElem = null;
        if (sigToken.equals(encrToken)) {
            // Use the same token
            encrTokId = sigTokId;
            encrTok = sigTok;
            encrTokElem = sigTokElem;
        } else {
            encrTokId = rmd.getIssuedEncryptionTokenId();
            encrTok = this.getToken(rmd, encrTokId);

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == encrToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == encrToken.getInclusion()
                    || (rmd.isInitiator() && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == encrToken
                            .getInclusion())) {
                encrTokElem = (Element) encrTok.getToken();

                // Add the encrToken element before the sigToken element
                RampartUtil.insertSiblingBefore(rmd, sigTokElem, encrTokElem);
            }

        }

        Vector encrParts = RampartUtil.getEncryptedParts(rmd);

        // Check for signature protection
        if (rpd.isSignatureProtection() && this.mainSigId != null) {
            // Now encrypt the signature using the above token
            encrParts.add(new WSEncryptionPart(this.mainSigId, "Element"));
        }

        if (rmd.isInitiator()) {
            for (int i = 0; i < encryptedTokensIdList.size(); i++) {
                encrParts
                        .add(new WSEncryptionPart((String) encryptedTokensIdList.get(i), "Element"));
            }
        }

        Element refList = null;
        if (encrParts.size() > 0) {
            // The sec conv token can be used without derived keys
            if (encrToken.isDerivedKeys()) {

                try {
                    WSSecDKEncrypt dkEncr = new WSSecDKEncrypt();

                    // Check whether it is security policy 1.2 and use the secure conversation
                    // accordingly
                    if (SPConstants.SP_V12 == encrToken.getVersion()) {
                        dkEncr.setWscVersion(ConversationConstants.VERSION_05_12);
                    }

                    if (encrTokElem != null && encrTok.getAttachedReference() != null) {

                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc.importNode(
                                (Element) encrTok.getAttachedReference(), true));
                    } else if (encrTok.getUnattachedReference() != null) {
                        dkEncr.setExternalKey(encrTok.getSecret(), (Element) doc.importNode(
                                (Element) encrTok.getUnattachedReference(), true));
                    } else if (!rmd.isInitiator() && encrToken.isDerivedKeys()) {

                        // If the Encrypted key used to create the derived key is not
                        // attached use key identifier as defined in WSS1.1 section
                        // 7.7 Encrypted Key reference
                        SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                        if (encrTok instanceof EncryptedKeyToken) {
                            tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken) encrTok)
                                    .getSHA1());
                        }
                        dkEncr.setExternalKey(encrTok.getSecret(), tokenRef.getElement());

                    } else {
                        dkEncr.setExternalKey(encrTok.getSecret(), encrTok.getId());
                    }

                    if (encrTok instanceof EncryptedKeyToken) {
                        dkEncr.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#"
                                + WSConstants.ENC_KEY_VALUE_TYPE);
                    }

                    dkEncr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    dkEncr.setDerivedKeyLength(rpd.getAlgorithmSuite()
                            .getEncryptionDerivedKeyLength() / 8);
                    dkEncr.prepare(doc);
                    Element encrDKTokenElem = null;
                    encrDKTokenElem = dkEncr.getdktElement();
                    if (encrTokElem != null) {
                        RampartUtil.insertSiblingAfter(rmd, encrTokElem, encrDKTokenElem);
                    } else if (timestampElement != null) {
                        RampartUtil.insertSiblingAfter(rmd, this.timestampElement, encrDKTokenElem);
                    } else {
                        RampartUtil.insertSiblingBefore(rmd, this.getInsertionLocation(),
                                encrDKTokenElem);
                    }

                    refList = dkEncr.encryptForExternalRef(null, encrParts);

                    RampartUtil.insertSiblingAfter(rmd, encrDKTokenElem, refList);

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInDKEncr");
                } catch (ConversationException e) {
                    throw new RampartException("errorInDKEncr");
                }
            } else {
                try {

                    WSSecEncrypt encr = new WSSecEncrypt();

                    encr.setWsConfig(rmd.getConfig());
                    // Hack to handle reference id issues
                    // TODO Need a better fix
                    if (encrTokId.startsWith("#")) {
                        encrTokId = encrTokId.substring(1);
                    }
                    encr.setEncKeyId(encrTokId);

                    if (krbToken == null) {
                        encr.setEphemeralKey(encrTok.getSecret());
                        RampartUtil.setEncryptionUser(rmd, encr);
                        encr.setSymmetricEncAlgorithm(rpd.getAlgorithmSuite().getEncryption());
                    } else {
                        if (encrTok != null) {
                            byte[] secret = encrTok.getSecret();
                            int factor = 0;
                            if (rmd.getPolicyData().getRampartConfig() != null) {
                                KerberosConfig config = null;
                                String fac = null;
                                config = rmd.getPolicyData().getRampartConfig().getKerberosConfig();
                                if ((fac = config.getProp().getProperty(
                                        KerberosConfig.KDC_DES_AES_FACTOR)) != null) {
                                    try {
                                        factor = Integer.parseInt(fac);
                                    } catch (Exception e) {
                                        factor = 0;
                                    }
                                }
                            }

                            if (factor > 1) {
                                byte[] newSecret = new byte[secret.length * 4];
                                int j = 0;
                                for (int i = 0; i < newSecret.length; i++) {
                                    newSecret[i] = secret[j++];
                                    if (j == secret.length)
                                        j = 0;
                                }
                                encr.setEphemeralKey(newSecret);
                                encrTok.setSecret(newSecret);
                            } else {
                                encr.setEphemeralKey(secret);
                                encrTok.setSecret(secret);
                            }
                            ((EncryptedKeyToken) encrTok).setSHA1(krbToken.getKrbSession()
                                    .getThumbPrintEncoded());
                            try {
                                rmd.getTokenStorage().add(sigTok);
                            } catch (TrustException e) {
                                throw new RampartException("errorAddingKerbTokenToStore");
                            }
                        }
                    }

                    encr.setDocument(doc);
                    encr.setEncryptSymmKey(false);

                    // Use key identifier in the KeyInfo in server side
                    if (!rmd.isInitiator()) {
                        if (krbToken != null) {
                            encr.setUseKeyIdentifier(true);
                            encr.setKeyIdentifierType(WSConstants.KERBEROS_KEY_IDENTIFIER);
                        } else if (encrTok instanceof EncryptedKeyToken) {
                            encr.setUseKeyIdentifier(true);
                            encr.setCustomReferenceValue(((EncryptedKeyToken) encrTok).getSHA1());
                            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                        } else if (isIssuedToken) {
                            encr.setUseKeyIdentifier(true);
                            encr.setCustomReferenceValue(encrTokId);
                            encr.setKeyIdentifierType(WSConstants.SAML_ASSERTION_IDENTIFIER);
                            try {
                                // RampartUtil.insertSiblingAfter(rmd,this.timestampElement,getLLOMfromOM(encrTok.getToken()));
                            } catch (Exception e) {
                                log.debug("error while converting SAML issued token to a dom element");
                            }
                        }
                    }
                    encr.prepare(
                            doc,
                            RampartUtil.getEncryptionCrypto(rpd.getRampartConfig(),
                                    rmd.getCustomClassLoader()));

                    // Encrypt, get hold of the ref list and add it
                    refList = encr.encryptForExternalRef(null, encrParts);

                    if (encrTokElem != null) {
                        RampartUtil.insertSiblingAfter(rmd, encrTokElem, refList);
                    } else {
                        RampartUtil.insertSiblingBeforeOrPrepend(rmd, this.getInsertionLocation(),
                                refList);
                    }

                } catch (WSSecurityException e) {
                    throw new RampartException("errorInEncryption", e);
                }
            }
        }

        if (tlog.isDebugEnabled()) {
            t2 = System.currentTimeMillis();
            tlog.debug("Signature took :" + (t1 - t0) + ", Encryption took :" + (t2 - t1));
        }

    }

    /**
     * @param rmd
     * @param sigToken
     * @return
     * @throws RampartException
     */
    private String setupEncryptedKey(RampartMessageData rmd, Token sigToken)
            throws RampartException {
        try {
            WSSecEncryptedKey encrKey = this.getEncryptedKeyBuilder(rmd, sigToken);
            String id = encrKey.getId();
            byte[] secret = encrKey.getEphemeralKey();
            // Create a rahas token from this info and store it so we can use
            // it in the next steps

            Date created = new Date();
            Date expires = new Date();
            // TODO make this lifetime configurable ???
            expires.setTime(System.currentTimeMillis() + 300000);
            org.apache.rahas.EncryptedKeyToken tempTok = new org.apache.rahas.EncryptedKeyToken(id,
                    (OMElement) encrKey.getEncryptedKeyElement(), created, expires);

            tempTok.setSecret(secret);

            // Set the SHA1 value of the encrypted key, this is used when the encrypted
            // key is referenced via a key identifier of type EncryptedKeySHA1
            tempTok.setSHA1(getSHA1(encrKey.getEncryptedEphemeralKey()));

            rmd.getTokenStorage().add(tempTok);

            String bstTokenId = encrKey.getBSTTokenId();
            // If direct ref is used to refer to the cert
            // then add the cert to the sec header now
            if (bstTokenId != null && bstTokenId.length() > 0) {
                RampartUtil.appendChildToSecHeader(rmd, encrKey.getBinarySecurityTokenElement());
            }

            return id;

        } catch (TrustException e) {
            throw new RampartException("errorInAddingTokenIntoStore");
        }
    }

    private String getSHA1(byte[] input) throws RampartException {

        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e1) {
            throw new RampartException("noSHA1availabe", e1);
        }
        sha.reset();
        sha.update(input);
        byte[] data = sha.digest();

        return Base64.encode(data);
    }

    private String getEncryptedKey(RampartMessageData rmd) throws RampartException {

        Vector results = (Vector) rmd.getMsgContext().getProperty(WSHandlerConstants.RECV_RESULTS);

        for (int i = 0; i < results.size(); i++) {
            WSHandlerResult rResult = (WSHandlerResult) results.get(i);

            Vector wsSecEngineResults = rResult.getResults();

            for (int j = 0; j < wsSecEngineResults.size(); j++) {
                WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults.get(j);
                Integer actInt = (Integer) wser.get(WSSecurityEngineResult.TAG_ACTION);
                if (actInt.intValue() == WSConstants.ENCR) {

                    if (wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID) != null
                            && ((String) wser.get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID))
                                    .length() != 0) {

                        try {

                            String encryptedKeyID = (String) wser
                                    .get(WSSecurityEngineResult.TAG_ENCRYPTED_KEY_ID);

                            Date created = new Date();
                            Date expires = new Date();
                            expires.setTime(System.currentTimeMillis() + 300000);
                            EncryptedKeyToken tempTok = new EncryptedKeyToken(encryptedKeyID,
                                    created, expires);
                            tempTok.setSecret((byte[]) wser
                                    .get(WSSecurityEngineResult.TAG_DECRYPTED_KEY));
                            tempTok.setSHA1(getSHA1((byte[]) wser
                                    .get(WSSecurityEngineResult.TAG_ENCRYPTED_EPHEMERAL_KEY)));
                            rmd.getTokenStorage().add(tempTok);

                            return encryptedKeyID;

                        } catch (TrustException e) {
                            throw new RampartException("errorInAddingTokenIntoStore");
                        }

                    }
                }
            }
        }
        return null;
    }

}


text:
<?php

namespace Drupal\file\Element;

use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Symfony\Component\HttpFoundation\Request;

/**
 * Provides an AJAX/progress aware widget for uploading and saving a file.
 *
 * @FormElement("managed_file")
 */
class ManagedFile extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#process' => [
        [$class, 'processManagedFile'],
      ],
      '#element_validate' => [
        [$class, 'validateManagedFile'],
      ],
      '#pre_render' => [
        [$class, 'preRenderManagedFile'],
      ],
      '#theme' => 'file_managed_file',
      '#theme_wrappers' => ['form_element'],
      '#progress_indicator' => 'throbber',
      '#progress_message' => NULL,
      '#upload_validators' => [],
      '#upload_location' => NULL,
      '#size' => 22,
      '#multiple' => FALSE,
      '#extended' => FALSE,
      '#attached' => [
        'library' => ['file/drupal.file'],
      ],
      '#accept' => NULL,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    // Find the current value of this field.
    $fids = !empty($input['fids']) ? explode(' ', $input['fids']) : [];
    foreach ($fids as $key => $fid) {
      $fids[$key] = (int) $fid;
    }
    $force_default = FALSE;

    // Process any input and save new uploads.
    if ($input !== FALSE) {
      $input['fids'] = $fids;
      $return = $input;

      // Uploads take priority over all other values.
      if ($files = file_managed_file_save_upload($element, $form_state)) {
        if ($element['#multiple']) {
          $fids = array_merge($fids, array_keys($files));
        }
        else {
          $fids = array_keys($files);
        }
      }
      else {
        // Check for #filefield_value_callback values.
        // Because FAPI does not allow multiple #value_callback values like it
        // does for #element_validate and #process, this fills the missing
        // functionality to allow File fields to be extended through FAPI.
        if (isset($element['#file_value_callbacks'])) {
          foreach ($element['#file_value_callbacks'] as $callback) {
            $callback($element, $input, $form_state);
          }
        }

        // Load files if the FIDs have changed to confirm they exist.
        if (!empty($input['fids'])) {
          $fids = [];
          foreach ($input['fids'] as $fid) {
            if ($file = File::load($fid)) {
              $fids[] = $file->id();
              // Temporary files that belong to other users should never be
              // allowed.
              if ($file->isTemporary()) {
                if ($file->getOwnerId() != \Drupal::currentUser()->id()) {
                  $force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,
                // they are not allowed to reuse temporary files at all. But
                // they do need to be able to reuse their own files from earlier
                // submissions of the same form, so to allow that, check for the
                // token added by $this->processManagedFile().
                elseif (\Drupal::currentUser()->isAnonymous()) {
                  $token = NestedArray::getValue($form_state->getUserInput(), array_merge($element['#parents'], ['file_' . $file->id(), 'fid_token']));
                  if ($token !== Crypt::hmacBase64('file-' . $file->id(), \Drupal::service('private_key')->get() . Settings::getHashSalt())) {
                    $force_default = TRUE;
                    break;
                  }
                }
              }
            }
          }
          if ($force_default) {
            $fids = [];
          }
        }
      }
    }

    // If there is no input or if the default value was requested above, use the
    // default value.
    if ($input === FALSE || $force_default) {
      if ($element['#extended']) {
        $default_fids = isset($element['#default_value']['fids']) ? $element['#default_value']['fids'] : [];
        $return = isset($element['#default_value']) ? $element['#default_value'] : ['fids' => []];
      }
      else {
        $default_fids = isset($element['#default_value']) ? $element['#default_value'] : [];
        $return = ['fids' => []];
      }

      // Confirm that the file exists when used as a default value.
      if (!empty($default_fids)) {
        $fids = [];
        foreach ($default_fids as $fid) {
          if ($file = File::load($fid)) {
            $fids[] = $file->id();
          }
        }
      }
    }

    $return['fids'] = $fids;
    return $return;
  }

  /**
   * #ajax callback for managed_file upload forms.
   *
   * This ajax callback takes care of the following things:
   *   - Ensures that broken requests due to too big files are caught.
   *   - Adds a class to the response to be able to highlight in the UI, that a
   *     new file got uploaded.
   *
   * @param array $form
   *   The build form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The ajax response of the ajax upload.
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $form_parents = explode('/', $request->query->get('element_parents'));

    // Retrieve the element to be rendered.
    $form = NestedArray::getValue($form, $form_parents);

    // Add the special AJAX class if a new file was added.
    $current_file_count = $form_state->get('file_upload_delta_initial');
    if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
      $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
    }
    // Otherwise just add the new content class on a placeholder.
    else {
      $form['#suffix'] .= '';
    }

    $status_messages = ['#type' => 'status_messages'];
    $form['#prefix'] .= $renderer->renderRoot($status_messages);
    $output = $renderer->renderRoot($form);

    $response = new AjaxResponse();
    $response->setAttachments($form['#attached']);

    return $response->addCommand(new ReplaceCommand(NULL, $output));
  }

  /**
   * Render API callback: Expands the managed_file element type.
   *
   * Expands the file type to include Upload and Remove buttons, as well as
   * support for a default value.
   */
  public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {

    // This is used sometimes so let's implode it just once.
    $parents_prefix = implode('_', $element['#parents']);

    $fids = isset($element['#value']['fids']) ? $element['#value']['fids'] : [];

    // Set some default element properties.
    $element['#progress_indicator'] = empty($element['#progress_indicator']) ? 'none' : $element['#progress_indicator'];
    $element['#files'] = !empty($fids) ? File::loadMultiple($fids) : FALSE;
    $element['#tree'] = TRUE;

    // Generate a unique wrapper HTML ID.
    $ajax_wrapper_id = Html::getUniqueId('ajax-wrapper');

    $ajax_settings = [
      'callback' => [get_called_class(), 'uploadAjaxCallback'],
      'options' => [
        'query' => [
          'element_parents' => implode('/', $element['#array_parents']),
        ],
      ],
      'wrapper' => $ajax_wrapper_id,
      'effect' => 'fade',
      'progress' => [
        'type' => $element['#progress_indicator'],
        'message' => $element['#progress_message'],
      ],
    ];

    // Set up the buttons first since we need to check if they were clicked.
    $element['upload_button'] = [
      '#name' => $parents_prefix . '_upload_button',
      '#type' => 'submit',
      '#value' => t('Upload'),
      '#attributes' => ['class' => ['js-hide']],
      '#validate' => [],
      '#submit' => ['file_managed_file_submit'],
      '#limit_validation_errors' => [$element['#parents']],
      '#ajax' => $ajax_settings,
      '#weight' => -5,
    ];

    // Force the progress indicator for the remove button to be either 'none' or
    // 'throbber', even if the upload button is using something else.
    $ajax_settings['progress']['type'] = ($element['#progress_indicator'] == 'none') ? 'none' : 'throbber';
    $ajax_settings['progress']['message'] = NULL;
    $ajax_settings['effect'] = 'none';
    $element['remove_button'] = [
      '#name' => $parents_prefix . '_remove_button',
      '#type' => 'submit',
      '#value' => $element['#multiple'] ? t('Remove selected') : t('Remove'),
      '#validate' => [],
      '#submit' => ['file_managed_file_submit'],
      '#limit_validation_errors' => [$element['#parents']],
      '#ajax' => $ajax_settings,
      '#weight' => 1,
    ];

    $element['fids'] = [
      '#type' => 'hidden',
      '#value' => $fids,
    ];

    // Add progress bar support to the upload if possible.
    if ($element['#progress_indicator'] == 'bar' && $implementation = file_progress_implementation()) {
      $upload_progress_key = mt_rand();

      if ($implementation == 'uploadprogress') {
        $element['UPLOAD_IDENTIFIER'] = [
          '#type' => 'hidden',
          '#value' => $upload_progress_key,
          '#attributes' => ['class' => ['file-progress']],
          // Uploadprogress extension requires this field to be at the top of
          // the form.
          '#weight' => -20,
        ];
      }
      elseif ($implementation == 'apc') {
        $element['APC_UPLOAD_PROGRESS'] = [
          '#type' => 'hidden',
          '#value' => $upload_progress_key,
          '#attributes' => ['class' => ['file-progress']],
          // Uploadprogress extension requires this field to be at the top of
          // the form.
          '#weight' => -20,
        ];
      }

      // Add the upload progress callback.
      $element['upload_button']['#ajax']['progress']['url'] = Url::fromRoute('file.ajax_progress', ['key' => $upload_progress_key]);
    }

    // The file upload field itself.
    $element['upload'] = [
      '#name' => 'files[' . $parents_prefix . ']',
      '#type' => 'file',
      '#title' => t('Choose a file'),
      '#title_display' => 'invisible',
      '#size' => $element['#size'],
      '#multiple' => $element['#multiple'],
      '#theme_wrappers' => [],
      '#weight' => -10,
      '#error_no_message' => TRUE,
    ];
    if (!empty($element['#accept'])) {
      $element['upload']['#attributes'] = ['accept' => $element['#accept']];
    }

    if (!empty($fids) && $element['#files']) {
      foreach ($element['#files'] as $delta => $file) {
        $file_link = [
          '#theme' => 'file_link',
          '#file' => $file,
        ];
        if ($element['#multiple']) {
          $element['file_' . $delta]['selected'] = [
            '#type' => 'checkbox',
            '#title' => \Drupal::service('renderer')->renderPlain($file_link),
          ];
        }
        else {
          $element['file_' . $delta]['filename'] = $file_link + ['#weight' => -10];
        }
        // Anonymous users who have uploaded a temporary file need a
        // non-session-based token added so $this->valueCallback() can check
        // that they have permission to use this file on subsequent submissions
        // of the same form (for example, after an Ajax upload or form
        // validation error).
        if ($file->isTemporary() && \Drupal::currentUser()->isAnonymous()) {
          $element['file_' . $delta]['fid_token'] = [
            '#type' => 'hidden',
            '#value' => Crypt::hmacBase64('file-' . $delta, \Drupal::service('private_key')->get() . Settings::getHashSalt()),
          ];
        }
      }
    }

    // Add the extension list to the page as JavaScript settings.
    if (isset($element['#upload_validators']['file_validate_extensions'][0])) {
      $extension_list = implode(',', array_filter(explode(' ', $element['#upload_validators']['file_validate_extensions'][0])));
      $element['upload']['#attached']['drupalSettings']['file']['elements']['#' . $element['#id']] = $extension_list;
    }

    // Let #id point to the file element, so the field label's 'for' corresponds
    // with it.
    $element['#id'] = &$element['upload']['#id'];

    // Prefix and suffix used for Ajax replacement.
    $element['#prefix'] = '
';
    $element['#suffix'] = '
';

    return $element;
  }

  /**
   * Render API callback: Hides display of the upload or remove controls.
   *
   * Upload controls are hidden when a file is already uploaded. Remove controls
   * are hidden when there is no file attached. Controls are hidden here instead
   * of in \Drupal\file\Element\ManagedFile::processManagedFile(), because
   * #access for these buttons depends on the managed_file element's #value. See
   * the documentation of \Drupal\Core\Form\FormBuilderInterface::doBuildForm()
   * for more detailed information about the relationship between #process,
   * #value, and #access.
   *
   * Because #access is set here, it affects display only and does not prevent
   * JavaScript or other untrusted code from submitting the form as though
   * access were enabled. The form processing functions for these elements
   * should not assume that the buttons can't be "clicked" just because they are
   * not displayed.
   *
   * @see \Drupal\file\Element\ManagedFile::processManagedFile()
   * @see \Drupal\Core\Form\FormBuilderInterface::doBuildForm()
   */
  public static function preRenderManagedFile($element) {
    // If we already have a file, we don't want to show the upload controls.
    if (!empty($element['#value']['fids'])) {
      if (!$element['#multiple']) {
        $element['upload']['#access'] = FALSE;
        $element['upload_button']['#access'] = FALSE;
      }
    }
    // If we don't already have a file, there is nothing to remove.
    else {
      $element['remove_button']['#access'] = FALSE;
    }
    return $element;
  }

  /**
   * Render API callback: Validates the managed_file element.
   */
  public static function validateManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
    $clicked_button = end($form_state->getTriggeringElement()['#parents']);
    if ($clicked_button != 'remove_button' && !empty($element['fids']['#value'])) {
      $fids = $element['fids']['#value'];
      foreach ($fids as $fid) {
        if ($file = File::load($fid)) {
          // If referencing an existing file, only allow if there are existing
          // references. This prevents unmanaged files from being deleted if
          // this item were to be deleted. When files that are no longer in use
          // are automatically marked as temporary (now disabled by default),
          // it is not safe to reference a permanent file without usage. Adding
          // a usage and then later on removing it again would delete the file,
          // but it is unknown if and where it is currently referenced. However,
          // when files are not marked temporary (and then removed)
          // automatically, it is safe to add and remove usages, as it would
          // simply return to the current state.
          // @see https://www.drupal.org/node/2891902
          if ($file->isPermanent() && \Drupal::config('file.settings')->get('make_unused_managed_files_temporary')) {
            $references = static::fileUsage()->listUsage($file);
            if (empty($references)) {
              // We expect the field name placeholder value to be wrapped in t()
              // here, so it won't be escaped again as it's already marked safe.
              $form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
            }
          }
        }
        else {
          // We expect the field name placeholder value to be wrapped in t()
          // here, so it won't be escaped again as it's already marked safe.
          $form_state->setError($element, t('The file referenced by the @name field does not exist.', ['@name' => $element['#title']]));
        }
      }
    }

    // Check required property based on the FID.
    if ($element['#required'] && empty($element['fids']['#value']) && !in_array($clicked_button, ['upload_button', 'remove_button'])) {
      // We expect the field name placeholder value to be wrapped in t()
      // here, so it won't be escaped again as it's already marked safe.
      $form_state->setError($element, t('@name field is required.', ['@name' => $element['#title']]));
    }

    // Consolidate the array value of this field to array of FIDs.
    if (!$element['#extended']) {
      $form_state->setValueForElement($element, $element['fids']['#value']);
    }
  }

  /**
   * Wraps the file usage service.
   *
   * @return \Drupal\file\FileUsage\FileUsageInterface
   */
  protected static function fileUsage() {
    return \Drupal::service('file.usage');
  }

}

redpajama_set_name: RedPajamaGithub


text:
  User.where(email: "loveo@kth.se").first_or_create do |user|
    user.password = "secret",
    user.confirmed_at = Time.now
  end


text:
<?php

namespace Coramer\Sigtec\CoreBundle\Service;

/**
 * Generate the sequence of entities
 *
 * @author Carlos Mendoza <inhack20@tecnocreaciones.com>
 */
class SequenceGenerator
{
    /**
     *
     * @var \Tecnocreaciones\Bundle\ToolsBundle\Service\SequenceGenerator
     */
    private $sequenceGenerator;

    /**
     * Generate sequence plants from your company
     * @param \Coramer\Sigtec\CompanyBundle\Entity\Company $company
     * @return string
     */
    public function getNextNamePlant(\Coramer\Sigtec\CompanyBundle\Entity\Company $company) {
        $qb = $this->sequenceGenerator->createQueryBuilder();
        $qb
            ->from('Coramer\Sigtec\CompanyBundle\Entity\Plant', 'p')
            ->join('p.company', 'c')
            ->where('c.id = :company')
            ->setParameter('company', $company)
            ;
        $mask = 'Planta {000}';
        return $this->sequenceGenerator->generateNext($qb,$mask,'name');
    }

    function getNextTempArchive()
    {
        $qb = $this->sequenceGenerator->createQueryBuilder();
        $qb->from('Coramer\Sigtec\ReportTechnicalBundle\Entity\ReportTechnical', 'rt')
            ;
        return $this->sequenceGenerator->generateNextTemp($qb,'archive');
    }

    public function setSequenceGenerator(\Tecnocreaciones\Bundle\ToolsBundle\Service\SequenceGenerator $sequenceGenerator) {
        $this->sequenceGenerator = $sequenceGenerator;
    }
}


text:
<bill session="110" type="s" number="437" updated="2009-01-09T12:05:01-05:00">
	<status><introduced date="1170133200" datetime="2007-01-30"/></status>

	<introduced date="1170133200" datetime="2007-01-30"/>
	<titles>
		<title type="official" as="introduced">A bill to provide for the conveyance of an A-12 Blackbird aircraft to the Minnesota Air National Guard Historical Foundation.</title>
	</titles>
	<sponsor id="300024"/>
	<cosponsors>
		<cosponsor id="412242" joined="2007-01-30"/>
	</cosponsors>
	<actions>
		<action date="1170133200" datetime="2007-01-30"><text>Sponsor introductory remarks on measure. (CR S1351)</text></action>
		<action date="1170133200" datetime="2007-01-30"><text>Read twice and referred to the Committee on Armed Services.</text><reference label="text of measure as introduced" ref="CR S1351"/></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	1/30/2007--Introduced.
Directs the Secretary of the Air Force to convey to the Minnesota Air National Guard Historical Foundation, Inc., an A-12 Blackbird aircraft with tail number 60-6931 that is under the jurisdiction of the National Museum of the United States Air Force, and as of January 1, 2007, was on loan to the Foundation and on display with the 133rd Airlift Wing at Minneapolis-St. Paul International Airport, Minnesota.

</bill>


text:
file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*")

set(CPP_FILES
  qclickablelabel.cpp
  QmitkAboutDialog.cpp
  QmitkBasePropertyView.cpp
  QmitkBoolPropertyWidget.cpp
  QmitkBoundingObjectWidget.cpp
  QmitkCallbackFromGUIThread.cpp
  QmitkColorPropertyEditor.cpp
  QmitkColorPropertyView.cpp
  QmitkColorTransferFunctionCanvas.cpp
  QmitkCrossWidget.cpp
  QmitkEditPointDialog.cpp
  QmitkEnumerationPropertyWidget.cpp
  QmitkFFmpegWriter.cpp
  QmitkFileChooser.cpp
  QmitkGnuplotWidget.cpp
  QmitkHistogram.cpp
  QmitkHotkeyLineEdit.cpp
  QmitkModulesDialog.cpp
  QmitkModuleTableModel.cpp
  QmitkNumberPropertyEditor.cpp
  QmitkNumberPropertySlider.cpp
  QmitkNumberPropertyView.cpp
  QmitkPiecewiseFunctionCanvas.cpp
  QmitkPlotDialog.cpp
  QmitkPlotWidget.cpp
  QmitkPointListModel.cpp
  QmitkPointListView.cpp
  QmitkPointListWidget.cpp
  QmitkPrimitiveMovieNavigatorWidget.cpp
  QmitkPropertyViewFactory.cpp
  QmitkSliceWidget.cpp
  QmitkStandardViews.cpp
  QmitkStringPropertyEditor.cpp
  QmitkStringPropertyOnDemandEdit.cpp
  QmitkStringPropertyView.cpp
  QmitkTransferFunctionCanvas.cpp
  QmitkTransferFunctionGeneratorWidget.cpp
  QmitkTransferFunctionWidget.cpp
  QmitkUGCombinedRepresentationPropertyWidget.cpp
  QmitkVideoBackground.cpp
  QtWidgetsExtRegisterClasses.cpp
)

set(MOC_H_FILES
  include/qclickablelabel.h
  include/QmitkAboutDialog.h
  include/QmitkBasePropertyView.h
  include/QmitkBoolPropertyWidget.h
  include/QmitkBoundingObjectWidget.h
  include/QmitkCallbackFromGUIThread.h
  include/QmitkColorPropertyEditor.h
  include/QmitkColorPropertyView.h
  include/QmitkColorTransferFunctionCanvas.h
  include/QmitkCrossWidget.h
  include/QmitkEditPointDialog.h
  include/QmitkEnumerationPropertyWidget.h
  include/QmitkFFmpegWriter.h
  include/QmitkFileChooser.h
  include/QmitkGnuplotWidget.h
  include/QmitkHotkeyLineEdit.h
  include/QmitkNumberPropertyEditor.h
  include/QmitkNumberPropertySlider.h
  include/QmitkNumberPropertyView.h
  include/QmitkPiecewiseFunctionCanvas.h
  include/QmitkPlotWidget.h
  include/QmitkPointListModel.h
  include/QmitkPointListView.h
  include/QmitkPointListWidget.h
  include/QmitkPrimitiveMovieNavigatorWidget.h
  include/QmitkSliceWidget.h
  include/QmitkStandardViews.h
  include/QmitkStringPropertyEditor.h
  include/QmitkStringPropertyOnDemandEdit.h
  include/QmitkStringPropertyView.h
  include/QmitkTransferFunctionCanvas.h
  include/QmitkTransferFunctionGeneratorWidget.h
  include/QmitkTransferFunctionWidget.h
  include/QmitkUGCombinedRepresentationPropertyWidget.h
  include/QmitkVideoBackground.h
)

set(UI_FILES
  src/QmitkAboutDialogGUI.ui
  src/QmitkGnuplotWidget.ui
  src/QmitkPrimitiveMovieNavigatorWidget.ui
  src/QmitkSliceWidget.ui
  src/QmitkTransferFunctionGeneratorWidget.ui
  src/QmitkTransferFunctionWidget.ui
)

set(QRC_FILES
  resource/QtWidgetsExt.qrc
)


text: Rails.application.config.session_store :cookie_store, key: '_my-really-simple-store_session'


text:
package io.quarkus.deployment.builditem.nativeimage;

import java.util.Objects;

import io.quarkus.builder.item.MultiBuildItem;

/**
 * Register a JVM module to be enabled via GraalVM's {@code --add-modules}
 * argument.
 * Not all modules are enabled by default, and some libraries might
 * need to enlist some of the non-default modules to be activated.
 */
public final class NativeImageEnableModule extends MultiBuildItem {

    private final String moduleName;

    public NativeImageEnableModule(String moduleName) {
        this.moduleName = Objects.requireNonNull(moduleName);
    }

    public String getModuleName() {
        return moduleName;
    }
}


text:
package org.apache.mina.example.haiku;

/**
 * @author Apache Mina Project (dev@mina.apache.org)
 * @version $Rev$, $Date$
 */
public class PhraseUtilities {
    static int countSyllablesInPhrase(String phrase) {
        int syllables = 0;

        String[] words = phrase.split("[^\\w-]+");
        for (int i = 0, max = words.length; i < max; i++) {
            String word = words[i];
            if (word.length() > 0) {
                syllables += countSyllablesInWord(word.toLowerCase());
            }
        }

        return syllables;
    }

    static int countSyllablesInWord(String word) {
        char[] chars = word.toCharArray();
        int syllables = 0;
        boolean lastWasVowel = false;

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (isVowel(c)) {
                if (!lastWasVowel
                        || (i > 0 && isE(chars, i - 1) && isO(chars, i))) {
                    ++syllables;
                    lastWasVowel = true;
                }
            } else {
                lastWasVowel = false;
            }
        }

        if (word.endsWith("oned") || word.endsWith("ne")
                || word.endsWith("ide") || word.endsWith("ve")
                || word.endsWith("fe") || word.endsWith("nes")
                || word.endsWith("mes")) {
            --syllables;
        }

        return syllables;
    }

    static boolean isE(char[] chars, int position) {
        return isCharacter(chars, position, 'e');
    }

    static boolean isCharacter(char[] chars, int position, char c) {
        return chars[position] == c;
    }

    static boolean isO(char[] chars, int position) {
        return isCharacter(chars, position, 'o');
    }

    static boolean isVowel(char c) {
        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
                || c == 'y';
    }
}


text:
package com.centurylink.mdw.workflow.activity.process;

import com.centurylink.mdw.activity.ActivityException;
import com.centurylink.mdw.activity.types.StartActivity;
import com.centurylink.mdw.annotations.Activity;
import com.centurylink.mdw.util.log.StandardLogger.LogLevel;
import com.centurylink.mdw.util.timer.Tracked;
import com.centurylink.mdw.workflow.activity.DefaultActivityImpl;

import java.util.Map;

/**
 * Base class for all the ProcessStart Controlled Activity
 * This class will be extended by the custom ProcessStart activity
 */
@Tracked(LogLevel.TRACE)
@Activity(value="Process Start", category=StartActivity.class, icon="shape:start",
        pagelet="com.centurylink.mdw.base/processStart.pagelet")
public class ProcessStartActivity extends DefaultActivityImpl implements StartActivity {

    private static final String PARAMETERS = "Parameters";

    /**
     * Default constructor with params
     */
    public ProcessStartActivity(){
        super();
    }

    @Override
    public void execute() throws ActivityException {
        try {
            if (getAttributes().containsKey(PARAMETERS)) {
                Map<String,String> parameters = getAttributes().getMap(PARAMETERS);
                for (String key : parameters.keySet()) {
                    String one = parameters.get(key);
                    if (valueIsJavaExpression(one)) {
                        Object request = getVariableValue("request");
                        if (request != null) {
                            Object value = getRuntimeContext().evaluate(one);
                            // do not override input values set explicitly with
                            // null ones from xpath (eg: HandleOrder demo)
                            if (value != null)
                                setVariableValue(key, value);
                        }
                    }
                }
            }
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}


text:
package apollo.gui.tweeker;

import java.awt.Color;

import apollo.datamodel.Range;
import apollo.datamodel.RangeI;
import apollo.datamodel.SequenceI;

public class CutSite extends Range {
  private RestrictionEnzyme enzyme;
  boolean palindrome = false;
  boolean export = false;

  public CutSite(int start,
                 int end,
                 RestrictionEnzyme enzyme) {
    super(enzyme == null ? "stub" : enzyme.getName(), start, end);
    this.enzyme = enzyme;
    this.setFeatureType("cutsite");
  }

  public RestrictionEnzyme getRestrictionEnzyme() {
    return this.enzyme;
  }

  public boolean isPalindrome() {
    return palindrome;
  }

  public void setPalindromic(boolean palindrome) {
    this.palindrome = palindrome;
  }

  public void exportFragment(boolean export) {
    this.export = export;
  }

  public boolean exportFragment() {
    return export;
  }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>REST API in your Meteor App</title>

		<meta name="description" content="REST API in your Meteor App">
		<meta name="author" content="vst42">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/default.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

REST API in Meteor

Integrate your apps easily

						Created by vst42

						Software entrepeneur / consultant

Meteor: new way to build your apps

Modern user interface

Browser and Mobile

Live updates

Ultra responsive

Radically less code

One language everywhere

REST: Let the world use your app!

Integrations, integrations, integrations

GET /api/collection - all published data

POST /api/collection - insert a document into collection

GET /api/collection/:id - find one published document

PUT /api/collection/:id - update a document

DELETE /api/collection/:id - remove a document

Meteor REST Packages

From low to high-level

Iron.Router

http-methods

http-publish

Iron.Router

Full control of REST request

meteor add iron-router

Router.map(function() {
    this.route('/api/test', {
        where: 'server',
        action: function() {
            this.response.writeHead(200, {'Content-Type': 'application/json'});
            this.response.end('{"gotBody":"' + this.request.body + '"}');
        }
    });
});

http-methods

Less detailed, but still powerful

meteor add cfs:http-methods

HTTP.methods({
  'api/time': function() {
    return new Date().toString();
  }
});

http-publish

Just publish your collections over REST

meteor add cfs:http-publish

Orders = new Meteor.Collection('orders');

HTTP.publish({collection: Orders}, function(data) {
  return Orders.find({});
});

Live action!

Adding RESTful API to Meteor demo app

The End


text:
// Copyright (C) 2015 Victor Baybekov

namespace QuikSharp.DataStructures
{
    /// <summary>
    /// При обработке изменения денежного лимита функция getMoney возвращает таблицу Lua с параметрами:
    /// </summary>
    public class MoneyLimit {
        // ReSharper disable InconsistentNaming
        /// <summary>
        /// Входящий лимит по денежным средствам
        /// </summary>
        public double money_open_limit { get; set; }

        /// <summary>
        /// Стоимость немаржинальных бумаг в заявках на покупку
        /// </summary>
        public double money_limit_locked_nonmarginal_value { get; set; }
        /// <summary>
        /// Заблокированное в заявках на покупку количество денежных средств
        /// </summary>
        public double money_limit_locked { get; set; }
        /// <summary>
        /// Входящий остаток по денежным средствам
        /// </summary>
        public double money_open_balance { get; set; }
        /// <summary>
        /// Текущий лимит по денежным средствам
        /// </summary>
        public double money_current_limit { get; set; }
        /// <summary>
        /// Текущий остаток по денежным средствам
        /// </summary>
        public double money_current_balance { get; set; }
        /// <summary>
        /// Доступное количество денежных средств
        /// </summary>
        public double money_limit_available { get; set; }
        // ReSharper restore InconsistentNaming
    }
}


text:
@interface MJUnderlinedButton : UIButton

+ (MJUnderlinedButton*)underlinedButton;

@end


text:
/*jshint browser:true jquery:true*/
define(["jquery"], function($){
    "use strict";
    $(document).on("login",function() {
        $("[data-captcha='guest_checkout'], [data-captcha='register_during_checkout']").hide();
        $("[role='guest_checkout'], [role='register_during_checkout']").hide();
        var type = ($("#login\\:guest").is(':checked')) ? 'guest_checkout' : 'register_during_checkout';
        $("[role='" + type + "'], [data-captcha='" + type + "']").show();
    }).on('billingSave', function() {
            $(".captcha-reload:visible").trigger("click");
        });
});


text:
import ConfigParser

#Keys read from ConfigParser are all lower cased!

'''SECTIONS'''
SECTION_SERVER              = 'Server'
SERVER_ROLE                 = 'role'
SERVER_HOSTNAME             = 'hostname'
SERVER_PORT                 = 'port'
SERVER_SCHEDULER_HOSTNAME   = 'scheduler_hostname'
SERVER_SCHEDULER_PORT       = 'scheduler_port'
SERVER_SMTP_ADDRESS			= 'smtp_address'
SERVER_FROM_ADDRESS			= 'from_address'
SERVER_MAIL_USERNAME		= 'mail_username'
SERVER_MAIL_PASSWORD		= 'mail_password'
SCHEDULE_FILES_PATH			= 'schedule_files_path'
SERVER_KEYS = [SERVER_ROLE, SERVER_HOSTNAME, SERVER_PORT, SERVER_SMTP_ADDRESS, SERVER_FROM_ADDRESS,
				SERVER_MAIL_USERNAME, SERVER_MAIL_PASSWORD, SCHEDULE_FILES_PATH]

'''PROCESS NODE Keys'''
SECTION_PROCESS_NODE        	= 'Process_Node'
PROCESS_NODE_NAME           	= 'computer_name'
PROCESS_NODE_THREADS        	= 'num_threads'
PROCESS_NODE_DATABASE_NAME  	= 'database_name'
PROCESS_NODE_PATH_ALIAS			= 'path_alias'
PROCESS_NODE_SOFTWARE_LIST		= 'software_list'
PROCESS_NODE_KEYS = [PROCESS_NODE_NAME, PROCESS_NODE_THREADS, PROCESS_NODE_DATABASE_NAME, PROCESS_NODE_SOFTWARE_LIST]

'''MONITOR keys'''
SECTION_MONITOR = 'Monitor'
MONITOR_JOBS_PATH           = 'jobs_path'
MONITOR_PROCESSING_PATH     = 'processing_path'
MONITOR_FINISHED_INFO_PATH  = 'finished_info_path'
MONITOR_DONE_PATH           = 'done_path'
MONITOR_COMPUTER_NAME       = 'computer_name'
MONITOR_DIR_ALIAS           = 'dir_alias'
MONITOR_CHECK_INTERVAL      = 'check_interval'
MONITOR_KEYS = [MONITOR_JOBS_PATH, MONITOR_PROCESSING_PATH, MONITOR_FINISHED_INFO_PATH, MONITOR_DONE_PATH,
				MONITOR_COMPUTER_NAME, MONITOR_DIR_ALIAS, MONITOR_CHECK_INTERVAL]

SECTION_JOB_DIR_ROOTS = 'JobDirRoots'

'''LISTS'''
SECTIONS = [SECTION_SERVER, SECTION_PROCESS_NODE, SECTION_MONITOR]

'''CLASSES'''

class SettingsIO:
	def __init__(self):
		self.config = ConfigParser.ConfigParser()
		self.settingDicts = dict()

	def load(self, filename):
		print 'Settings loading file:', filename
		self.config.read(filename)
		for sec in self.config.sections():
			self.settingDicts[sec] = self.__get_sect_dict__(sec)

	def getSetting(self, section):
		if section in self.settingDicts:
			return self.settingDicts[section]
		else:
			return dict()

	def checkSectionKeys(self, section_name, keys):
		for k in keys:
			sect = self.getSetting(section_name)
			if not k in sect:
				print 'Could not find Key:', k, 'in server settings'
				return False
		return True

	def __get_sect_dict__(self, section):
		dict1 = {}
		options = self.config.options(section)
		for option in options:
			try:
				dict1[option] = self.config.get(section, option)
				if dict1[option] == -1:
					print("skip: %s" % option)
			except:
				print("exception on %s!" % option)
				dict1[option] = None
		return dict1

if __name__ == '__main__':
	# test
	s = SettingsIO()
	s.load('settings.ini')
	print 'all sections',s.settingDicts.keys()
	schedDict = s.getSetting('Scheduler')
	print 'scheduler section', schedDict.keys()


text:
from broca.pipeline import Pipe

class Tokenizer(Pipe):
    input = Pipe.type.docs
    output = Pipe.type.tokens

    def __call__(self, docs):
        return self.tokenize(docs)

    def tokenize(self, docs):
        raise NotImplementedError

from .lemma import Lemma


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SystemsStatus.Core.Data.Entities;
using SystemsStatus.Core.Data.Repositories;
using NHibernate;

namespace SystemsStatus.Data.Repositories.Nh
{
    public class NhUserRoleRepository : NhRepositoryBase<int?, UserRole>, IUserRoleRepository
    {
        public NhUserRoleRepository(ISession _session)
            : base(_session)
        {

        }
    }
}


text:
import pitcher = require("../../lib/runtime");

export class Module implements pitcher.Module {
  includes = [OtherModule];

  providesPie() {
    return "peach";
  }
}

export class OtherModule implements pitcher.Module {
  contributesPie() {
    return ["apple"];
  }
}


text:
@interface EZPCustomsInfoSynchronousTests : XCTestCase
@property (strong) EZPClient *client;
@end

@implementation EZPCustomsInfoSynchronousTests

- (void)setUp {
    [super setUp];
    self.client = [EZPClient defaultClient];
}

- (void)tearDown {
    self.client = nil;
    [super tearDown];
}

@end


text:
package com.xiaogua.better.bean;

public class ExecuteImp implements Interface_Execute {

	public Object execute() {
		return "execute say hello";
	}

	public String execute(String command) {
		return "execute " + command;
	}

}


text:
//===============================================================================
// © 2015 eWorkplace Apps.  ALL rights reserved.
// Main Author: Shrey Sharma
// Original DATE: 5/19/2015
//===============================================================================
package com.eworkplaceapps.platform.utils.enums;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public enum EmailType {

    PERSONAL(1),
    WORK(2),
    OTHER(3);

    private int id;

    EmailType(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    /**
     *
     * @return  Map<Integer, String>
     */
    public static Map<Integer, String> getEmailTypeListAsDictionary() {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(EmailType.PERSONAL.getId(), "Personal");
        map.put(EmailType.WORK.getId(), "Work");
        map.put(EmailType.OTHER.getId(), "Other");
        return map;
    }
    /**
     *
     * @return Map<String, Integer>
     */
    public static Map<String, Integer> getEmailTypeDictionary() {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("personal", EmailType.PERSONAL.getId());
        map.put("work", EmailType.WORK.getId());
        map.put("other", EmailType.OTHER.getId());
        return map;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="10dp"
        app:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:minHeight="?attr/actionBarSize" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:text="@string/app_name"
                android:textSize="20sp" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="40dp"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginBottom="12dp"
                android:text="@string/version" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:autoLink="web"
                android:gravity="center"
                android:maxWidth="200dp"
                android:text="@string/github" />

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_margin="20dp"
                android:background="@color/gray_light" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:gravity="center"
                android:text="@string/licenseTitle"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:autoLink="web"
                android:text="@string/license" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>


text:
SET DEFINE OFF;
CREATE UNIQUE INDEX AFW_19_CLE_UK1 ON AFW_19_CLE
(REF_DISPN_FONCT, REF_LANG, INDIC_INTER, CODE_KEYPR, CODE_KEYDW,
INDIC_SHIFT, INDIC_ALT, INDIC_CTRL)
LOGGING
/


text:
class PrefService;
class PrefRegistrySimple;

namespace metrics {

// A LogStore implementation for storing UMA logs.
// This implementation keeps track of two types of logs, initial and ongoing,
// each stored in UnsentLogStore. It prioritizes staging initial logs over
// ongoing logs.
class MetricsLogStore : public LogStore {
 public:
  // Constructs a MetricsLogStore that persists data into |local_state|.
  // If max_log_size is non-zero, it will not persist ongoing logs larger than
  // |max_ongoing_log_size| bytes. |signing_key| is used to generate a signature
  // of a log, which will be uploaded to validate data integrity.
  MetricsLogStore(PrefService* local_state,
                  size_t max_ongoing_log_size,
                  const std::string& signing_key);
  ~MetricsLogStore();

  // Registers local state prefs used by this class.
  static void RegisterPrefs(PrefRegistrySimple* registry);

  // Saves |log_data| as the given type.
  void StoreLog(const std::string& log_data, MetricsLog::LogType log_type);

  // LogStore:
  bool has_unsent_logs() const override;
  bool has_staged_log() const override;
  const std::string& staged_log() const override;
  const std::string& staged_log_hash() const override;
  const std::string& staged_log_signature() const override;
  void StageNextLog() override;
  void DiscardStagedLog() override;
  void PersistUnsentLogs() const override;
  void LoadPersistedUnsentLogs() override;

  // Inspection methods for tests.
  size_t ongoing_log_count() const { return ongoing_log_queue_.size(); }
  size_t initial_log_count() const { return initial_log_queue_.size(); }

 private:
  // Tracks whether unsent logs (if any) have been loaded from the serializer.
  bool unsent_logs_loaded_;

  // Logs stored with the INITIAL_STABILITY_LOG type that haven't been sent yet.
  // These logs will be staged first when staging new logs.
  UnsentLogStore initial_log_queue_;
  // Logs stored with the ONGOING_LOG type that haven't been sent yet.
  UnsentLogStore ongoing_log_queue_;

  DISALLOW_COPY_AND_ASSIGN(MetricsLogStore);
};

}  // namespace metrics

#endif  // COMPONENTS_METRICS_METRICS_LOG_STORE_H_


text:
import sys
from subprocess import Popen, PIPE

from smac.tae.execute_ta_run import StatusType, ExecuteTARun

__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2015, ML4AAD"
__license__ = "3-clause BSD"
__maintainer__ = "Marius Lindauer"
__email__ = "lindauer@cs.uni-freiburg.de"
__version__ = "0.0.1"

class ExecuteTARunOld(ExecuteTARun):

    """
        executes a target algorithm run with a given configuration
        on a given instance and some resource limitations
        Uses the original SMAC/PILS format (SMAC < v2.10)
        Attributes
        ----------
        ta : string
            the command line call to the target algorithm (wrapper)
        run_obj: str
            run objective (runtime or quality)
        par_factor: int
            penalized average runtime factor
    """

    def run(self, config, instance=None,
            cutoff=None,
            seed=12345,
            instance_specific="0"
            ):
        """
            runs target algorithm <self.ta> with configuration <config> on
            instance <instance> with instance specifics <specifics>
            for at most <cutoff> seconds and random seed <seed>
            Parameters
            ----------
                config : dictionary (or similar)
                    dictionary param -> value
                instance : string
                    problem instance
                cutoff : double
                    runtime cutoff
                seed : int
                    random seed
                instance_specific: str
                    instance specific information (e.g., domain file or solution)
            Returns
            -------
                status: enum of StatusType (int)
                    {SUCCESS, TIMEOUT, CRASHED, ABORT}
                cost: float
                    cost/regret/quality/runtime (float) (None, if not returned by TA)
                runtime: float
                    runtime (None if not returned by TA)
                additional_info: dict
                    all further additional run information
        """

        if instance is None:
            instance = "0"
        if cutoff is None:
            cutoff = 99999999999999.

        # TOOD: maybe replace fixed instance specific and cutoff_length (0) to
        # other value
        cmd = []
        cmd.extend(self.ta)
        cmd.extend([instance, instance_specific, str(cutoff), "0", str(seed)])
        for p in config:
            if not config[p] is None:
                cmd.extend(["-" + str(p), str(config[p])])

        self.logger.debug("Calling: %s" % (" ".join(cmd)))
        p = Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        stdout_, stderr_ = p.communicate()

        self.logger.debug("Stdout: %s" % (stdout_))
        self.logger.debug("Stderr: %s" % (stderr_))

        status = "CRASHED"
        quality = 1234567890
        runtime = 1234567890
        additional_info = {}
        for line in stdout_.split("\n"):
            if line.startswith("Result of this algorithm run:") or line.startswith("Result for ParamILS") or line.startswith("Result for SMAC"):
                fields = line.split(":")[1].split(",")
                fields = list(map(lambda x: x.strip(" "), fields))
                if len(fields) == 5:
                    status, runtime, runlength, quality, seed = fields
                    additional_info = {}
                else:
                    status, runtime, runlength, quality, seed, additional_info = fields
                    additional_info = {"additional_info": additional_info}

                runtime = min(float(runtime), cutoff)
                quality = float(quality)
                seed = int(seed)

        if status in ["SAT", "UNSAT", "SUCCESS"]:
            status = StatusType.SUCCESS
        elif status in ["TIMEOUT"]:
            status = StatusType.TIMEOUT
        elif status in ["CRASHED"]:
            status = StatusType.CRASHED
        elif status in ["ABORT"]:
            status = StatusType.ABORT
            self.logger.error("Target algorithm returned ABORT -- Exit!")
            sys.exit(43)
        elif status in ["MEMOUT"]:
            status = StatusType.MEMOUT

        if status in [StatusType.CRASHED, StatusType.ABORT]:
            self.logger.warn(
                "Target algorithm crashed. Last 5 lines of stdout and stderr")
            self.logger.warn("\n".join(stdout_.split("\n")[-5:]))
            self.logger.warn("\n".join(stderr_.split("\n")[-5:]))

        if self.run_obj == "runtime":
            cost = runtime
        else:
            cost = quality

        return status, cost, float(runtime), additional_info

    def get_cmd_line(self, config, instance=None,
            cutoff=None,
            seed=12345,
            instance_specific="0"
            ):
        """

            return cmd line for target algorithm <self.ta> with configuration <config> on
            instance <instance> with instance specifics <specifics>
            for at most <cutoff> seconds and random seed <seed>
            Parameters
            ----------
                config : dictionary (or similar)
                    dictionary param -> value
                instance : string
                    problem instance
                cutoff : double
                    runtime cutoff
                seed : int
                    random seed
                instance_specific: str
                    instance specific information (e.g., domain file or solution)
            Returns
            -------
                cmd_line: string
                    cmd line that should be executed
        """

        if instance is None:
            instance = "0"
        if cutoff is None:
            cutoff = 99999999999999.

        # TOOD: maybe replace fixed instance specific and cutoff_length (0) to
        # other value
        cmd = []
        cmd.extend(self.ta)
        cmd.extend([instance, instance_specific, str(cutoff), "0", str(seed)])
        for p in config:
            if not config[p] is None:
                cmd.extend(["-" + str(p), str(config[p])])

        return " ".join(cmd)

    def process_output(self, stdout_, cutoff):
        """
            after running cmd line returned by get_cmd_line function, the output of execution
            is processed by this function

            Parameters
            ----------
                stdout_ : string
                    output of execution
                cutoff : double
                    runtime cutoff
            Returns
            -------
                status: enum of StatusType (int)
                    {SUCCESS, TIMEOUT, CRASHED, ABORT}
                cost: float
                    cost/regret/quality/runtime (float) (None, if not returned by TA)
                runtime: float
                    runtime (None if not returned by TA)
                additional_info: dict
                    all further additional run information
        """
        self.logger.debug("Stdout: %s" % (stdout_))

        status = "CRASHED"
        quality = 1234567890
        runtime = 1234567890
        additional_info = {}
        for line in stdout_.split("\n"):
            if line.startswith("Result of this algorithm run:") or line.startswith("Result for ParamILS") or line.startswith("Result for SMAC"):
                fields = line.split(":")[1].split(",")
                fields = list(map(lambda x: x.strip(" "), fields))
                if len(fields) == 5:
                    status, runtime, runlength, quality, seed = fields
                    additional_info = {}
                else:
                    status, runtime, runlength, quality, seed, additional_info = fields
                    additional_info = {"additional_info": additional_info}

                self.stats.ta_runs += 1
                self.stats.ta_time_used += float(runtime)
                runtime = min(float(runtime), cutoff)
                quality = float(quality)
                seed = int(seed)

        if status in ["SAT", "UNSAT", "SUCCESS"]:
            status = StatusType.SUCCESS
        elif status in ["TIMEOUT"]:
            status = StatusType.TIMEOUT
        elif status in ["CRASHED"]:
            status = StatusType.CRASHED
        elif status in ["ABORT"]:
            status = StatusType.ABORT
            self.logger.error("Target algorithm returned ABORT -- Exit!")
            sys.exit(43)
        elif status in ["MEMOUT"]:
            status = StatusType.MEMOUT

        if status in [StatusType.CRASHED, StatusType.ABORT]:
            self.logger.warn(
                "Target algorithm crashed. Last 5 lines of stdout")
            self.logger.warn("\n".join(stdout_.split("\n")[-5:]))

        if self.run_obj == "runtime":
            if status != StatusType.SUCCESS:
                cost = cutoff * self.par_factor
            else:
                cost = runtime
        else:
            cost = quality

        return status, cost, float(runtime), additional_info


text:
package org.hudsonci.servlets;

import javax.servlet.Servlet;
import java.util.HashMap;
import java.util.Map;

/**
 * {@link Servlet} registration details.
 *
 * @author Jason Dillon
 * @since 2.1.0
 */
public class ServletRegistration
    implements Cloneable
{
    private String name;

    private Class<? extends Servlet> servletType;

    private Servlet servlet;

    private String uriPrefix;

    private Map<String, String> parameters;

    public String getName() {
        return name;
    }

    public ServletRegistration setName(final String name) {
        this.name = name;
        return this;
    }

    public Class<? extends Servlet> getServletType() {
        return servletType;
    }

    public ServletRegistration setServletType(final Class<? extends Servlet> type) {
        this.servletType = type;
        return this;
    }

    public Servlet getServlet() {
        return servlet;
    }

    public ServletRegistration setServlet(final Servlet servlet) {
        this.servlet = servlet;
        return this;
    }

    public String getUriPrefix() {
        return uriPrefix;
    }

    public ServletRegistration setUriPrefix(final String path) {
        this.uriPrefix = path;
        return this;
    }

    public Map<String, String> getParameters() {
        if (parameters == null) {
            return new HashMap<String, String>();
        }
        return parameters;
    }

    public ServletRegistration setParameters(final Map<String, String> parameters) {
        this.parameters = parameters;
        return this;
    }

    public ServletRegistration addParameter(final String name, final String value) {
        getParameters().put(name, value);
        return this;
    }

    @Override
    public ServletRegistration clone() {
        try {
            return (ServletRegistration) super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw (InternalError) new InternalError().initCause(e);
        }
    }

    @Override
    public String toString() {
        return "ServletRegistration{" +
            "name='" + name + '\'' +
            ", servletType=" + servletType +
            ", servlet=" + servlet +
            ", uriPrefix='" + uriPrefix + '\'' +
            ", parameters=" + parameters +
            '}';
    }

    public static interface Handle
    {
        ServletRegistration getRegistration();

        void setEnabled(boolean enabled);

        boolean isEnabled();
    }
}


text:
Difficulty: Medium

https://leetcode.com/problems/2-keys-keyboard/

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
2. Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

**Example 1:**
```
Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
```
**Note:**
1. The n will be in the range [1, 1000].

Companies: Microsoft

Related Topics: Dynamic Programming

Similar Questions: 4 Keys Keyboard


text:
<component name="libraryTable">
  <library name="graphview-3.1.3">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.jjoe64/graphview/3.1.3/res" />
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.jjoe64/graphview/3.1.3/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
#ifndef _MD5_BASEFRAME_HPP
#define _MD5_BASEFRAME_HPP

#include <boost/fusion/include/adapt_struct.hpp>

namespace md5 {

  template< typename vec3 >
    struct baseframe_item {
      vec3 position;
      vec3 orientation;
    };

} /* namespace md5 */

  BOOST_FUSION_ADAPT_TPL_STRUCT
  (
   (vec3),
   (md5::baseframe_item)(vec3),
   (vec3, position)
   (vec3, orientation)
  )

#endif /* end of include guard: _MD5_BASEFRAME_HPP */


text:
package org.ovirt.engine.core.common.action;

import org.ovirt.engine.core.common.businessentities.*;

import javax.validation.Valid;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "EventSubscriptionParametesBase")
public class EventSubscriptionParametesBase extends VdcActionParametersBase {
    private static final long serialVersionUID = -6988075041053848616L;

    public EventSubscriptionParametesBase(event_subscriber event_subscriber, String domain) {
        setEventSubscriber(event_subscriber);
        setDomain(domain);
    }

    @Valid
    @XmlElement(name = "EventSubscriber")
    private event_subscriber privateEventSubscriber;

    public event_subscriber getEventSubscriber() {
        return privateEventSubscriber;
    }

    private void setEventSubscriber(event_subscriber value) {
        privateEventSubscriber = value;
    }

    @XmlElement(name = "Domain")
    private String privateDomain;

    public String getDomain() {
        return privateDomain;
    }

    private void setDomain(String value) {
        privateDomain = value;
    }

    public EventSubscriptionParametesBase() {
    }
}


text:
/*
 * This is a basic func test for a Common application.
 */
YUI({
    useConsoleOutput: true,
    useBrowserConsole: true,
    logInclude: { TestRunner: true }
}).use('node', 'node-event-simulate', 'test', 'console', function (Y) {

    var suite = new Y.Test.Suite("Common: assetcsswithlocationheaderserver");

    suite.add(new Y.Test.Case({

        "test assetcsswithlocationheaderserver": function() {
	        var pat1 = /\/static\/AssetsMojit\/assets\/css\/css1.css/gi;
            var pat2 = /\/static\/Binders\/assets\/css\/css_in_binders.css/gi;
            Y.Assert.areEqual('/static/AssetsMojit/assets/css/css1.css', checkscript(Y.one('head'), 'link', 'href', pat1));
            Y.Assert.areEqual('/static/Binders/assets/css/css_in_binders.css', checkscript(Y.one('head'), 'link', 'href', pat2));
        }
    }));

    Y.Test.Runner.add(suite);

    function checkscript(mynode, assetLoc, assetTag, assetPat){
         var mystring;
         mynode.all(assetLoc).each(function (taskNode){
             var mysrc = taskNode.get(assetTag).match(assetPat);
             if(mysrc!=null){ mystring=mysrc; }
         });
         return mystring;
    }
});