text:
package org.apache.ambari.server.serveraction.kerberos;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.security.credential.PrincipalKeyCredential;
import org.apache.ambari.server.utils.ShellCommandUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory;
import org.apache.directory.server.kerberos.shared.keytab.Keytab;
import org.apache.directory.server.kerberos.shared.keytab.KeytabEntry;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
import org.apache.directory.shared.kerberos.components.EncryptionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * KerberosOperationHandler is an abstract class providing basic implementations of common Kerberos
 * operations (like generating secure passwords) and placeholders for KDC-specific operations
 * (such as creating principals).
 */
public abstract class KerberosOperationHandler {
  private final static Logger LOG = LoggerFactory.getLogger(KerberosOperationHandler.class);

  /**
   * Kerberos-env configuration property name: ldap_url
   */
  public final static String KERBEROS_ENV_LDAP_URL = "ldap_url";

  /**
   * Kerberos-env configuration property name: container_dn
   */
  public final static String KERBEROS_ENV_PRINCIPAL_CONTAINER_DN = "container_dn";

  /**
   * Kerberos-env configuration property name: group
   */
  public final static String KERBEROS_ENV_USER_PRINCIPAL_GROUP = "ipa_user_group";

  /**
   * Kerberos-env configuration property name: ad_create_attributes_template
   */
  public final static String KERBEROS_ENV_AD_CREATE_ATTRIBUTES_TEMPLATE = "ad_create_attributes_template";

  /**
   * Kerberos-env configuration property name: kdc_create_attributes
   */
  public final static String KERBEROS_ENV_KDC_CREATE_ATTRIBUTES = "kdc_create_attributes";

  /**
   * Kerberos-env configuration property name: encryption_types
   */
  public final static String KERBEROS_ENV_ENCRYPTION_TYPES = "encryption_types";

  /**
   * Kerberos-env configuration property name: kdc_hosts
   */
  public final static String KERBEROS_ENV_KDC_HOSTS = "kdc_hosts";

  /**
   * Kerberos-env configuration property name: admin_server_host
   */
  public final static String KERBEROS_ENV_ADMIN_SERVER_HOST = "admin_server_host";

  /**
   * Kerberos-env configuration property name: kadmin_principal_name
   */
  public final static String KERBEROS_ENV_KADMIN_PRINCIPAL_NAME = "kadmin_principal_name";

  /**
   * Kerberos-env configuration property name: executable_search_paths
   */
  public final static String KERBEROS_ENV_EXECUTABLE_SEARCH_PATHS = "executable_search_paths";

  /**
   * An array of String values declaring the default (ordered) list of path to search for executables
   */
  private static final String[] DEFAULT_EXECUTABLE_SEARCH_PATHS = {"/usr/bin", "/usr/kerberos/bin", "/usr/sbin", "/usr/lib/mit/bin", "/usr/lib/mit/sbin"};

  /**
   * A Map of MIT KDC Encryption types to EncryptionType values.
   *

   * See http://web.mit.edu/kerberos/krb5-devel/doc/admin/conf_files/kdc_conf.html#encryption-types
   */
  private static final Map<String, Set<EncryptionType>> ENCRYPTION_TYPE_TRANSLATION_MAP = Collections.unmodifiableMap(
      new HashMap<String, Set<EncryptionType>>() {
        {
          // aes: The AES family: aes256-cts-hmac-sha1-96 and aes128-cts-hmac-sha1-96
          put("aes", EnumSet.of(EncryptionType.AES256_CTS_HMAC_SHA1_96, EncryptionType.AES128_CTS_HMAC_SHA1_96));

          // aes256-cts-hmac-sha1-96 aes256-cts:  AES-256	CTS mode with 96-bit SHA-1 HMAC
          put("aes256-cts-hmac-sha1-96", EnumSet.of(EncryptionType.AES256_CTS_HMAC_SHA1_96));
          put("aes256-cts", EnumSet.of(EncryptionType.AES256_CTS_HMAC_SHA1_96));
          put("aes-256", EnumSet.of(EncryptionType.AES256_CTS_HMAC_SHA1_96));

          // aes128-cts-hmac-sha1-96 aes128-cts AES-128:	CTS mode with 96-bit SHA-1 HMAC
          put("aes128-cts-hmac-sha1-96", EnumSet.of(EncryptionType.AES128_CTS_HMAC_SHA1_96));
          put("aes128-cts", EnumSet.of(EncryptionType.AES128_CTS_HMAC_SHA1_96));
          put("aes-128", EnumSet.of(EncryptionType.AES128_CTS_HMAC_SHA1_96));

          // rc4	The RC4 family: arcfour-hmac
          put("rc4", EnumSet.of(EncryptionType.RC4_HMAC));

          // arcfour-hmac rc4-hmac arcfour-hmac-md5:	RC4 with HMAC/MD5
          put("arcfour-hmac", EnumSet.of(EncryptionType.RC4_HMAC));
          put("rc4-hmac", EnumSet.of(EncryptionType.RC4_HMAC));
          put("arcfour-hmac-md5", EnumSet.of(EncryptionType.UNKNOWN));

          // arcfour-hmac-exp rc4-hmac-exp arcfour-hmac-md5-exp:	Exportable RC4 with HMAC/MD5 (weak)
          put("arcfour-hmac-exp", EnumSet.of(EncryptionType.RC4_HMAC_EXP));
          put("rc4-hmac-exp", EnumSet.of(EncryptionType.RC4_HMAC_EXP));
          put("arcfour-hmac-md5-exp", EnumSet.of(EncryptionType.UNKNOWN));

          // camellia 	The Camellia family: camellia256-cts-cmac and camellia128-cts-cmac
          put("camellia", EnumSet.of(EncryptionType.UNKNOWN));

          // camellia256-cts-cmac camellia256-cts:	Camellia-256 CTS mode with CMAC
          put("camellia256-cts-cmac", EnumSet.of(EncryptionType.UNKNOWN));
          put("camellia256-cts", EnumSet.of(EncryptionType.UNKNOWN));

          // camellia128-cts-cmac camellia128-cts:	Camellia-128 CTS mode with CMAC
          put("camellia128-cts-cmac", EnumSet.of(EncryptionType.UNKNOWN));
          put("camellia128-cts", EnumSet.of(EncryptionType.UNKNOWN));

          //des:	The DES family: des-cbc-crc, des-cbc-md5, and des-cbc-md4 (weak)
          put("des", EnumSet.of(EncryptionType.DES_CBC_CRC, EncryptionType.DES_CBC_MD5, EncryptionType.DES_CBC_MD4));

          // des-cbc-md4: DES cbc mode with RSA-MD4 (weak)
          put("des-cbc-md4", EnumSet.of(EncryptionType.DES_CBC_MD4));

          // des-cbc-md5:	DES cbc mode with RSA-MD5 (weak)
          put("des-cbc-md5", EnumSet.of(EncryptionType.DES_CBC_MD5));

          // des-cbc-crc:	DES cbc mode with CRC-32 (weak)
          put("des-cbc-crc", EnumSet.of(EncryptionType.DES_CBC_CRC));

          // des-cbc-raw: DES cbc mode raw (weak)
          put("des-cbc-raw", EnumSet.of(EncryptionType.UNKNOWN));

          // des-hmac-sha1: DES with HMAC/sha1 (weak)
          put("des-hmac-sha1", EnumSet.of(EncryptionType.UNKNOWN));

          // des3:	The triple DES family: des3-cbc-sha1
          put("des3", EnumSet.of(EncryptionType.DES3_CBC_SHA1_KD)); // Using DES3_CBC_SHA1_KD since DES3_CBC_SHA1 invalid key issues with KDC

          // des3-cbc-raw:	Triple DES cbc mode raw (weak)
          put("des3-cbc-raw", EnumSet.of(EncryptionType.UNKNOWN));

          // des3-cbc-sha1 des3-hmac-sha1 des3-cbc-sha1-kd:	Triple DES cbc mode with HMAC/sha1
          put("des3-cbc-sha1", EnumSet.of(EncryptionType.DES3_CBC_SHA1_KD)); // Using DES3_CBC_SHA1_KD since DES3_CBC_SHA1 invalid key issues with KDC
          put("des3-hmac-sha1", EnumSet.of(EncryptionType.UNKNOWN));
          put("des3-cbc-sha1-kd", EnumSet.of(EncryptionType.DES3_CBC_SHA1_KD));

        }
      }
  );

  /**
   * The default set of ciphers to use for creating keytab entries
   */
  private static final Set<EncryptionType> DEFAULT_CIPHERS = Collections.unmodifiableSet(
      new HashSet<EncryptionType>() {{
        add(EncryptionType.DES_CBC_MD5);
        add(EncryptionType.DES3_CBC_SHA1_KD);
        add(EncryptionType.RC4_HMAC);
        add(EncryptionType.AES128_CTS_HMAC_SHA1_96);
        add(EncryptionType.AES256_CTS_HMAC_SHA1_96);
      }});

  private PrincipalKeyCredential administratorCredential = null;
  private String defaultRealm = null;
  private Set<EncryptionType> keyEncryptionTypes = new HashSet<>(DEFAULT_CIPHERS);
  private boolean open = false;

  /**
   * An array of String indicating an ordered list of filesystem paths to use to search for executables
   * needed to perform Kerberos-related operations. For example, kadmin
   */
  private String[] executableSearchPaths = null;

  /**
   * Prepares and creates resources to be used by this KerberosOperationHandler.
   *

   * It is expected that this KerberosOperationHandler will not be used before this call.
   *
   * @param administratorCredential a PrincipalKeyCredential containing the administrative credential
   *                                for the relevant KDC
   * @param defaultRealm            a String declaring the default Kerberos realm (or domain)
   * @param kerberosConfiguration   a Map of key/value pairs containing data from the kerberos-env configuration set
   */
  public void open(PrincipalKeyCredential administratorCredential, String defaultRealm, Map<String, String> kerberosConfiguration)
      throws KerberosOperationException {

    setAdministratorCredential(administratorCredential);
    setDefaultRealm(defaultRealm);

    if (kerberosConfiguration != null) {
      setKeyEncryptionTypes(translateEncryptionTypes(kerberosConfiguration.get(KERBEROS_ENV_ENCRYPTION_TYPES), "\\s+"));
      setExecutableSearchPaths(kerberosConfiguration.get(KERBEROS_ENV_EXECUTABLE_SEARCH_PATHS));
    }
  }

  /**
   * Closes and cleans up any resources used by this KerberosOperationHandler
   *

   * It is expected that this KerberosOperationHandler will not be used after this call.
   */
  public void close() throws KerberosOperationException {
    setOpen(false);
  }

  /**
   * Test to see if the specified principal exists in a previously configured KDC
   *

   * The implementation is specific to a particular type of KDC.
   *
   * @param principal a String containing the principal to test
   * @param service   a boolean value indicating whether the principal is for a service or not
   * @return true if the principal exists; false otherwise
   * @throws KerberosOperationException
   */
  public abstract boolean principalExists(String principal, boolean service)
      throws KerberosOperationException;

  /**
   * Creates a new principal in a previously configured KDC
   *

   * The implementation is specific to a particular type of KDC.
   *
   * @param principal a String containing the principal to add
   * @param password  a String containing the password to use when creating the principal
   * @param service   a boolean value indicating whether the principal is to be created as a service principal or not
   * @return an Integer declaring the generated key number
   * @throws KerberosOperationException
   * @throws KerberosPrincipalAlreadyExistsException if the principal already exists
   */
  public abstract Integer createPrincipal(String principal, String password, boolean service)
      throws KerberosOperationException;

  /**
   * Updates the password for an existing principal in a previously configured KDC
   *

   * The implementation is specific to a particular type of KDC.
   *
   * @param principal a String containing the principal to update
   * @param password  a String containing the password to set
   * @param service   a boolean value indicating whether the principal is for a service or not
   * @return an Integer declaring the new key number
   * @throws KerberosOperationException
   * @throws KerberosPrincipalDoesNotExistException if the principal does not exist
   */
  public abstract Integer setPrincipalPassword(String principal, String password, boolean service)
      throws KerberosOperationException;

  /**
   * Removes an existing principal in a previously configured KDC
   *

   * The implementation is specific to a particular type of KDC.
   *
   * @param principal a String containing the principal to remove
   * @param service   a boolean value indicating whether the principal is for a service or not
   * @return true if the principal was successfully removed; otherwise false
   * @throws KerberosOperationException
   */
  public abstract boolean removePrincipal(String principal, boolean service)
      throws KerberosOperationException;

  /**
   * Tests to ensure the connection information and credentials allow for administrative
   * connectivity to the KDC
   *
   * @return true of successful; otherwise false
   * @throws KerberosOperationException if a failure occurs while testing the
   *                                    administrator credentials
   */
  public boolean testAdministratorCredentials() throws KerberosOperationException {
    if (!isOpen()) {
      throw new KerberosOperationException("This operation handler has not been opened");
    }

    PrincipalKeyCredential credential = getAdministratorCredential();
    if (credential == null) {
      throw new KerberosOperationException("Missing KDC administrator credential");
    } else {
      return principalExists(credential.getPrincipal(), false);
    }
  }

  /**
   * Create a keytab using the specified principal and password.
   *
   * @param principal a String containing the principal to test
   * @param password  a String containing the password to use when creating the principal
   * @param keyNumber a Integer indicating the key number for the keytab entries
   * @return the created Keytab
   * @throws KerberosOperationException
   */
  protected Keytab createKeytab(String principal, String password, Integer keyNumber)
      throws KerberosOperationException {

    if (StringUtils.isEmpty(principal)) {
      throw new KerberosOperationException("Failed to create keytab file, missing principal");
    }

    if (password == null) {
      throw new KerberosOperationException(String.format("Failed to create keytab file for %s, missing password", principal));
    }

    Set<EncryptionType> ciphers = new HashSet<>(keyEncryptionTypes);
    List<KeytabEntry> keytabEntries = new ArrayList<>();
    Keytab keytab = new Keytab();

    if (!ciphers.isEmpty()) {
      // Create a set of keys and relevant keytab entries
      Map<EncryptionType, EncryptionKey> keys = KerberosKeyFactory.getKerberosKeys(principal, password, ciphers);

      if (keys != null) {
        byte keyVersion = (keyNumber == null) ? 0 : keyNumber.byteValue();
        KerberosTime timestamp = new KerberosTime();

        for (EncryptionKey encryptionKey : keys.values()) {
          keytabEntries.add(new KeytabEntry(principal, 1, timestamp, keyVersion, encryptionKey));
        }

        keytab.setEntries(keytabEntries);
      }
    }

    return keytab;
  }

  /**
   * Create or append to a keytab file using keytab data from another keytab file.
   *

   * If the destination keytab file contains keytab data, that data will be merged with the new data
   * to create a composite set of keytab entries.
   *
   * @param sourceKeytabFile      a File containing the absolute path to the file with the keytab data to store
   * @param destinationKeytabFile a File containing the absolute path to where the keytab data is to be stored
   * @return true if the keytab file was successfully created; false otherwise
   * @throws KerberosOperationException
   * @see #createKeytabFile(org.apache.directory.server.kerberos.shared.keytab.Keytab, java.io.File)
   */
  protected boolean createKeytabFile(File sourceKeytabFile, File destinationKeytabFile)
      throws KerberosOperationException {
    return createKeytabFile(readKeytabFile(sourceKeytabFile), destinationKeytabFile);
  }

  /**
   * Create or append to a keytab file using the specified principal and password.
   *

   * If the destination keytab file contains keytab data, that data will be merged with the new data
   * to create a composite set of keytab entries.
   *
   * @param principal             a String containing the principal to test
   * @param password              a String containing the password to use when creating the principal
   * @param keyNumber             an Integer declaring the relevant key number to use for the keytabs entries
   * @param destinationKeytabFile a File containing the absolute path to where the keytab data is to be stored
   * @return true if the keytab file was successfully created; false otherwise
   * @throws KerberosOperationException
   * @see #createKeytabFile(org.apache.directory.server.kerberos.shared.keytab.Keytab, java.io.File)
   */
  protected boolean createKeytabFile(String principal, String password, Integer keyNumber, File destinationKeytabFile)
      throws KerberosOperationException {
    return createKeytabFile(createKeytab(principal, password, keyNumber), destinationKeytabFile);
  }

  /**
   * Create or append to a keytab file using the specified Keytab
   *

   * If the destination keytab file contains keytab data, that data will be merged with the new data
   * to create a composite set of keytab entries.
   *
   * @param keytab                the Keytab containing the data to add to the keytab file
   * @param destinationKeytabFile a File containing the absolute path to where the keytab data is to be stored
   * @return true if the keytab file was successfully created; false otherwise
   * @throws KerberosOperationException
   */
  public boolean createKeytabFile(Keytab keytab, File destinationKeytabFile)
      throws KerberosOperationException {

    if (destinationKeytabFile == null) {
      throw new KerberosOperationException("The destination file path is null");
    }

    try {
      mergeKeytabs(readKeytabFile(destinationKeytabFile), keytab).write(destinationKeytabFile);
      return true;
    } catch (IOException e) {
      String message = "Failed to export keytab file";
      LOG.error(message, e);

      if (!destinationKeytabFile.delete()) {
        destinationKeytabFile.deleteOnExit();
      }

      throw new KerberosOperationException(message, e);
    }
  }

  /**
   * Merge the keytab data from one keytab with the keytab data from a different keytab.
   *

   * If similar key entries exist for the same principal, the updated values will be used
   *
   * @param keytab  a Keytab with the base keytab data
   * @param updates a Keytab containing the updated keytab data
   * @return a Keytab with the merged data
   */
  protected Keytab mergeKeytabs(Keytab keytab, Keytab updates) {
    List<KeytabEntry> keytabEntries = (keytab == null)
        ? Collections.emptyList()
        : new ArrayList<>(keytab.getEntries());
    List<KeytabEntry> updateEntries = (updates == null)
        ? Collections.emptyList()
        : new ArrayList<>(updates.getEntries());
    List<KeytabEntry> mergedEntries = new ArrayList<>();

    if (keytabEntries.isEmpty()) {
      mergedEntries.addAll(updateEntries);
    } else if (updateEntries.isEmpty()) {
      mergedEntries.addAll(keytabEntries);
    } else {
      Iterator<KeytabEntry> iterator = keytabEntries.iterator();

      while (iterator.hasNext()) {
        KeytabEntry keytabEntry = iterator.next();

        for (KeytabEntry entry : updateEntries) {
          if (entry.getPrincipalName().equals(keytabEntry.getPrincipalName()) &&
              entry.getKey().getKeyType().equals(keytabEntry.getKey().getKeyType())) {
            iterator.remove();
            break;
          }
        }
      }

      mergedEntries.addAll(keytabEntries);
      mergedEntries.addAll(updateEntries);
    }

    Keytab mergedKeytab = new Keytab();
    mergedKeytab.setEntries(mergedEntries);
    return mergedKeytab;
  }

  /**
   * Reads a file containing keytab data into a new Keytab
   *
   * @param file A File containing the path to the file from which to read keytab data
   * @return a Keytab or null if the file was not readable
   */
  protected Keytab readKeytabFile(File file) {
    Keytab keytab;

    if (file.exists() && file.canRead() && (file.length() > 0)) {
      try {
        keytab = Keytab.read(file);
      } catch (IOException e) {
        // There was an issue reading in the existing keytab file... quietly assume no data
        keytab = null;
      }
    } else {
      keytab = null;
    }

    return keytab;
  }

  /**
   * Sets the KDC administrator credential.
   *
   * @return a credential
   */
  public PrincipalKeyCredential getAdministratorCredential() {
    return administratorCredential;
  }

  /**
   * Sets the administrator credentials for this KerberosOperationHandler.
   *

   * If the supplied {@link PrincipalKeyCredential} is not null, validates that the administrator
   * principal and values are not null or empty. If the credential value does not
   * validate, then a {@link KerberosAdminAuthenticationException} will be thrown.
   *
   * @param administratorCredential the KDC administrator credential
   * @throws KerberosAdminAuthenticationException if the non-null Credential fails to contain
   *                                              a non-empty principal and password values.
   */
  public void setAdministratorCredential(PrincipalKeyCredential administratorCredential)
      throws KerberosAdminAuthenticationException {

    // Ensure the credential is not null
    if (administratorCredential == null) {
      throw new KerberosAdminAuthenticationException("The administrator credential must not be null");
    }

    // Ensure the principal is not null or empty
    String principal = administratorCredential.getPrincipal();
    if (StringUtils.isEmpty(principal)) {
      throw new KerberosAdminAuthenticationException("Must specify a principal but it is null or empty");
    }

    // Ensure either the password or the keytab value is not null or empty
    char[] password = administratorCredential.getKey();
    if (ArrayUtils.isEmpty(password)) {
      throw new KerberosAdminAuthenticationException("Must specify a password but it is null or empty");
    }

    this.administratorCredential = administratorCredential;
  }

  public String getDefaultRealm() {
    return defaultRealm;
  }

  public void setDefaultRealm(String defaultRealm) {
    this.defaultRealm = defaultRealm;
  }

  /**
   * Gets the encryption algorithms used to encrypt keys in keytab entries
   *
   * @return a Set of EncryptionKey values indicating which algorithms are to be used when
   * encrypting keys for keytab entries.
   */
  public Set<EncryptionType> getKeyEncryptionTypes() {
    return keyEncryptionTypes;
  }

  /**
   * Sets the encryption algorithms to use to encrypt keys in keytab entries
   *

   * If set to null the default set of ciphers will be used.  See {@link #DEFAULT_CIPHERS}
   *
   * @param keyEncryptionTypes a Set of EncryptionKey values or null to indicate the default set
   */
  public void setKeyEncryptionTypes(Set<EncryptionType> keyEncryptionTypes) {
    this.keyEncryptionTypes = Collections.unmodifiableSet(new HashSet<>(
        (keyEncryptionTypes == null)
            ? DEFAULT_CIPHERS
            : keyEncryptionTypes
    ));
  }

  /**
   * Gets the ordered array of search paths used to find Kerberos-related executables.
   *
   * @return an array of String values indicating an order list of filesystem paths to search
   */
  public String[] getExecutableSearchPaths() {
    return executableSearchPaths;
  }

  /**
   * Sets the ordered array of search paths used to find Kerberos-related executables.
   *

   * If null, a default set of paths will be assumed when searching:
   *

   *
/usr/bin

   *
/usr/kerberos/bin

   *
/usr/sbin

   *
/usr/lib/mit/bin

   *
/usr/lib/mit/sbin

   *

   *
   * @param executableSearchPaths an array of String values indicating an ordered list of filesystem paths to search
   */
  public void setExecutableSearchPaths(String[] executableSearchPaths) {
    this.executableSearchPaths = executableSearchPaths;
  }

  /**
   * Sets the ordered array of search paths used to find Kerberos-related executables.
   *

   * If null, a default set of paths will be assumed when searching:
   *

   *
/usr/bin

   *
/usr/kerberos/bin

   *
/usr/sbin

   *

   *
   * @param delimitedExecutableSearchPaths a String containing a comma-delimited (ordered) list of filesystem paths to search
   */
  public void setExecutableSearchPaths(String delimitedExecutableSearchPaths) {
    List<String> searchPaths = null;

    if (delimitedExecutableSearchPaths != null) {
      searchPaths = new ArrayList<>();
      for (String path : delimitedExecutableSearchPaths.split(",")) {
        path = path.trim();
        if (!path.isEmpty()) {
          searchPaths.add(path);
        }
      }
    }

    setExecutableSearchPaths((searchPaths == null) ? null : searchPaths.toArray(new String[searchPaths.size()]));
  }

  /**
   * Test this KerberosOperationHandler to see whether is was previously open or not
   *
   * @return a boolean value indicating whether this KerberosOperationHandler was open (true) or not (false)
   */
  public boolean isOpen() {
    return open;
  }

  /**
   * Sets whether this KerberosOperationHandler is open or not.
   *
   * @param open a boolean value indicating whether this KerberosOperationHandler was open (true) or not (false)
   */
  public void setOpen(boolean open) {
    this.open = open;
  }

  /**
   * Given base64-encoded keytab data, decode the String to binary data and write it to a (temporary)
   * file.
   *

   * Upon success, a new file is created.  The caller is expected to clean up this file when done
   * with it.
   *
   * @param keytabData a String containing base64-encoded keytab data
   * @return a File pointing to the decoded keytab file or null if not successful
   * @throws KerberosOperationException
   */
  protected File createKeytabFile(String keytabData)
      throws KerberosOperationException {
    boolean success = false;
    File tempFile = null;

    // Create a temporary file
    try {
      tempFile = File.createTempFile("temp", ".dat");
    } catch (IOException e) {
      LOG.error(String.format("Failed to create temporary keytab file: %s", e.getLocalizedMessage()), e);
    }

    if ((tempFile != null) && (keytabData != null)) {
      OutputStream fos = null;

      // Decoded the base64-encoded String and write it to the temporary file
      try {
        fos = new FileOutputStream(tempFile);
        fos.write(Base64.decodeBase64(keytabData));
        success = true;
      } catch (IOException e) {
        String message = String.format("Failed to write to temporary keytab file %s: %s",
            tempFile.getAbsolutePath(), e.getLocalizedMessage());
        LOG.error(message, e);
        throw new KerberosOperationException(message, e);
      } finally {
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            // Ignore this...
          }
        }

        // If there was an issue, clean up the file
        if (!success) {
          if (!tempFile.delete()) {
            tempFile.deleteOnExit();
          }

          tempFile = null;
        }
      }
    }

    return tempFile;
  }

  /**
   * Executes a shell command.
   *

   * See {@link org.apache.ambari.server.utils.ShellCommandUtil#runCommand(String[], Map<String,String>)}
   *
   * @param command            an array of String value representing the command and its arguments
   * @param envp               a map of string, string of environment variables
   * @param interactiveHandler a handler to provide responses to queries from the command,
   *                           or null if no queries are expected
   * @return a ShellCommandUtil.Result declaring the result of the operation
   * @throws KerberosOperationException
   */
  protected ShellCommandUtil.Result executeCommand(String[] command, Map<String, String> envp, ShellCommandUtil.InteractiveHandler interactiveHandler)
      throws KerberosOperationException {

    if ((command == null) || (command.length == 0)) {
      return null;
    } else {
      try {
        return ShellCommandUtil.runCommand(command, envp, interactiveHandler, false);
      } catch (IOException e) {
        String message = String.format("Failed to execute the command: %s", e.getLocalizedMessage());
        LOG.error(message, e);
        throw new KerberosOperationException(message, e);
      } catch (InterruptedException e) {
        String message = String.format("Failed to wait for the command to complete: %s", e.getLocalizedMessage());
        LOG.error(message, e);
        throw new KerberosOperationException(message, e);
      }
    }
  }

  /**
   * Executes a shell command.
   *

   * See {@link org.apache.ambari.server.utils.ShellCommandUtil#runCommand(String[])}
   *
   * @param command an array of String value representing the command and its arguments
   * @return a ShellCommandUtil.Result declaring the result of the operation
   * @throws KerberosOperationException
   * @see #executeCommand(String[], Map, ShellCommandUtil.InteractiveHandler)
   */
  protected ShellCommandUtil.Result executeCommand(String[] command)
      throws KerberosOperationException {
    return executeCommand(command, null);
  }

  /**
   * Executes a shell command.
   *

   * See {@link org.apache.ambari.server.utils.ShellCommandUtil#runCommand(String[])}
   *
   * @param command            an array of String value representing the command and its arguments
   * @param interactiveHandler a handler to provide responses to queries from the command,
   *                           or null if no queries are expected
   * @return a ShellCommandUtil.Result declaring the result of the operation
   * @throws KerberosOperationException
   * @see #executeCommand(String[], Map, ShellCommandUtil.InteractiveHandler)
   */
  protected ShellCommandUtil.Result executeCommand(String[] command, ShellCommandUtil.InteractiveHandler interactiveHandler) throws KerberosOperationException {
    return executeCommand(command, null, interactiveHandler);
  }

  /**
   * Given a principal, attempt to create a new DeconstructedPrincipal
   *
   * @param principal a String containing the principal to deconstruct
   * @return a DeconstructedPrincipal
   * @throws KerberosOperationException
   */
  protected DeconstructedPrincipal createDeconstructPrincipal(String principal) throws KerberosOperationException {
    try {
      return DeconstructedPrincipal.valueOf(principal, getDefaultRealm());
    } catch (IllegalArgumentException e) {
      throw new KerberosOperationException(e.getMessage(), e);
    }
  }

  /**
   * Given a cipher (or algorithm) name, attempts to translate it into an EncryptionType value.
   *

   * If a translation is not able to be made, {@link org.apache.directory.shared.kerberos.codec.types.EncryptionType#UNKNOWN}
   * is returned.
   *
   * @param name a String containing the name of the cipher to translate
   * @return an EncryptionType
   */
  protected Set<EncryptionType> translateEncryptionType(String name) {
    Set<EncryptionType> encryptionTypes = null;

    if (!StringUtils.isEmpty(name)) {
      encryptionTypes = ENCRYPTION_TYPE_TRANSLATION_MAP.get(name.toLowerCase());
    }

    if (encryptionTypes == null) {
      LOG.warn("The given encryption type name ({}) is not supported.", name);
      return Collections.emptySet();
    }

    return encryptionTypes;
  }

  /**
   * Given a delimited set of encryption type names, attempts to translate into a set of EncryptionType
   * values.
   *
   * @param names     a String containing a delimited list of encryption type names
   * @param delimiter a String declaring the delimiter to use to split names, if null, " " is used.
   * @return a Set of EncryptionType values
   * @throws KerberosOperationException When all the encryption type names are not supported
   */
  protected Set<EncryptionType> translateEncryptionTypes(String names, String delimiter)
      throws KerberosOperationException {
    Set<EncryptionType> encryptionTypes = new HashSet<>();

    if (!StringUtils.isEmpty(names)) {
      for (String name : names.split((delimiter == null) ? "\\s+" : delimiter)) {
        encryptionTypes.addAll(translateEncryptionType(name.trim()));
      }
    }

    if (encryptionTypes.isEmpty()) {
      throw new KerberosOperationException("All the encryption type names you set are not supported. Aborting.");
    }
    return encryptionTypes;
  }

  /**
   * Iterates through the characters in a string to escape special characters
   *
   * @param string             the String to process
   * @param charactersToEscape a Set of characters declaring the special characters to escape
   * @param escapeCharacter    a character to use for escaping
   * @return the string with escaped characters
   */
  protected String escapeCharacters(String string, Set<Character> charactersToEscape, Character escapeCharacter) {
    if (StringUtils.isEmpty(string) || (charactersToEscape == null) || charactersToEscape.isEmpty()) {
      return string;
    } else {
      StringBuilder builder = new StringBuilder();

      for (char character : string.toCharArray()) {
        if (charactersToEscape.contains(character)) {
          builder.append(escapeCharacter);
        }
        builder.append(character);
      }

      return builder.toString();
    }
  }

  /**
   * Given the name of an executable, searches the configured executable search path for an executable
   * file with that name.
   *
   * @param executable a String declaring the name of the executable to find within the search path
   * @return the absolute path of the found execute or the name of the executable if not found
   * within the search path
   * @see #setExecutableSearchPaths(String)
   * @see #setExecutableSearchPaths(String[])
   */
  protected String getExecutable(String executable) {
    String[] searchPaths = getExecutableSearchPaths();
    String executablePath = null;

    if (searchPaths == null) {
      searchPaths = DEFAULT_EXECUTABLE_SEARCH_PATHS;
    }

    for (String searchPath : searchPaths) {
      File executableFile = new File(searchPath, executable);

      if (executableFile.canExecute()) {
        executablePath = executableFile.getAbsolutePath();
        break;
      }
    }

    return (executablePath == null) ? executable : executablePath;
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/pixi/renderers/WebGLBatch.js - Pixi.JS</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.0.0

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AssetLoader

BaseTexture

CanvasRenderer

DisplayObject

DisplayObjectContainer

InteractionData

InteractionManager

MovieClip

Point

Rectangle

Sprite

SpriteSheetLoader

Stage

Texture

TilingSprite

WebGLBatch

WebGLRenderer

PIXI

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: src/pixi/renderers/WebGLBatch.js

/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

PIXI._batchs = [];

/**
 * @private
 */
PIXI._getBatch = function(gl)
{
	if(PIXI._batchs.length == 0)
	{
		return new PIXI.WebGLBatch(gl);
	}
	else
	{
		return PIXI._batchs.pop();
	}
}

/**
 * @private
 */
PIXI._returnBatch = function(batch)
{
	batch.clean();
	PIXI._batchs.push(batch);
}

/**
 * @private
 */
PIXI._restoreBatchs = function(gl)
{
	for (var i=0; i < PIXI._batchs.length; i++)
	{
	  PIXI._batchs[i].restoreLostContext(gl);
	};
}

/**
 * A WebGLBatch Enables a group of sprites to be drawn using the same settings.
 * if a group of sprites all have the same baseTexture and blendMode then they can be grouped into a batch. All the sprites in a batch can then be drawn in one go by the GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch even if the batch only contains one sprite. Batching is handled automatically by the webGL renderer. A good tip is: the smaller the number of batchs there are, the faster the webGL renderer will run.
 * @class WebGLBatch
 * @param an instance of the webGL context
 * @return {PIXI.renderers.WebGLBatch} WebGLBatch {@link PIXI.renderers.WebGLBatch}
 */
PIXI.WebGLBatch = function(gl)
{
	this.gl = gl;

	this.size = 0;

	this.vertexBuffer =  gl.createBuffer();
	this.indexBuffer =  gl.createBuffer();
	this.uvBuffer =  gl.createBuffer();
	this.colorBuffer =  gl.createBuffer();
	this.blendMode = PIXI.blendModes.NORMAL;
	this.dynamicSize = 1;
}

// constructor
PIXI.WebGLBatch.constructor = PIXI.WebGLBatch;

/**
 * Cleans the batch so that is can be returned to an object pool and reused
 */
PIXI.WebGLBatch.prototype.clean = function()
{
	this.verticies = [];
	this.uvs = [];
	this.indices = [];
	this.colors = [];
	//this.sprites = [];
	this.dynamicSize = 1;
	this.texture = null;
	this.last = null;
	this.size = 0;

	this.head;
	this.tail;
}

/*
 * recreates the buffers in the event of a context loss
 */
PIXI.WebGLBatch.prototype.restoreLostContext = function(gl)
{
	this.gl = gl;
	this.vertexBuffer =  gl.createBuffer();
	this.indexBuffer =  gl.createBuffer();
	this.uvBuffer =  gl.createBuffer();
	this.colorBuffer =  gl.createBuffer();
}

/**
 * inits the batch's texture and blend mode based if the supplied sprite
 * @method init
 * @param sprite {Sprite} the first sprite to be added to the batch. Only sprites with the same base texture and blend mode will be allowed to be added to this batch
 */
PIXI.WebGLBatch.prototype.init = function(sprite)
{
	sprite.batch = this;
	this.dirty = true;
	this.blendMode = sprite.blendMode;
	this.texture = sprite.texture.baseTexture;
//	this.sprites.push(sprite);
	this.head = sprite;
	this.tail = sprite;
	this.size = 1;

	this.growBatch();
}

/**
 * inserts a sprite before the specified sprite
 * @method insertBefore
 * @param sprite {Sprite} the sprite to be added
 * @param nextSprite {nextSprite} the first sprite will be inserted before this sprite
 */
PIXI.WebGLBatch.prototype.insertBefore = function(sprite, nextSprite)
{
	this.size++;

	sprite.batch = this;
	this.dirty = true;
	var tempPrev = nextSprite.__prev;
	nextSprite.__prev = sprite;
	sprite.__next = nextSprite;

	if(tempPrev)
	{
		sprite.__prev = tempPrev;
		tempPrev.__next = sprite;
	}
	else
	{
		this.head = sprite;
		//this.head.__prev = null
	}
}

/**
 * inserts a sprite after the specified sprite
 * @method insertAfter
 * @param sprite {Sprite} the sprite to be added
 * @param  previousSprite {Sprite} the first sprite will be inserted after this sprite
 */
PIXI.WebGLBatch.prototype.insertAfter = function(sprite, previousSprite)
{
	this.size++;

	sprite.batch = this;
	this.dirty = true;

	var tempNext = previousSprite.__next;
	previousSprite.__next = sprite;
	sprite.__prev = previousSprite;

	if(tempNext)
	{
		sprite.__next = tempNext;
		tempNext.__prev = sprite;
	}
	else
	{
		this.tail = sprite
	}

}

/**
 * removes a sprite from the batch
 * @method remove
 * @param sprite {Sprite} the sprite to be removed
 */
PIXI.WebGLBatch.prototype.remove = function(sprite)
{
	this.size--;

	if(this.size == 0)
	{
		sprite.batch = null;
		sprite.__prev = null;
		sprite.__next = null;
		return;
	}

	if(sprite.__prev)
	{
		sprite.__prev.__next = sprite.__next;
	}
	else
	{
		this.head = sprite.__next;
		this.head.__prev = null;
	}

	if(sprite.__next)
	{
		sprite.__next.__prev = sprite.__prev;
	}
	else
	{
		this.tail = sprite.__prev;
		this.tail.__next = null
	}

	sprite.batch = null;
	sprite.__next = null;
	sprite.__prev = null;
	this.dirty = true;
}

/**
 * Splits the batch into two with the specified sprite being the start of the new batch.
 * @method split
 * @param sprite {Sprite} the sprite that indicates where the batch should be split
 * @return {WebGLBatch} the new batch
 */
PIXI.WebGLBatch.prototype.split = function(sprite)
{

	//console.log("Splitting batch :" + this.size)
//	console.log(sprite)
//	console.log("-------")
	this.dirty = true;

	//var val = (this.tail == this.head)
	//console.log(val + " SAME?");
	var batch = new PIXI.WebGLBatch(this.gl)//PIXI._getBatch(this.gl);
	batch.init(sprite);
	batch.tail = this.tail;
	//console.log("id is " +batcheee.id)

	this.tail = sprite.__prev;
	this.tail.__next = null;

	sprite.__prev = null;
	// return a splite batch!
	//sprite.__prev.__next = null;
	//sprite.__prev = null;

	// TODO this size is wrong!
	// need to recalculate :/ problem with a linked list!
	// unless it gets calculated in the "clean"?

	// need to loop through items as there is no way to know the length on a linked list :/
	var tempSize = 0;
	while(sprite)
	{
		tempSize++;
		sprite.batch = batch;
		sprite = sprite.__next;
	}

	batch.size = tempSize;
	this.size -= tempSize;

	return batch;
}

/**
 * Merges two batchs together
 * @method merge
 * @param batch {WebGLBatch} the batch that will be merged
 */
PIXI.WebGLBatch.prototype.merge = function(batch)
{
	this.dirty = true;

	this.tail.__next = batch.head;
	batch.head.__prev = this.tail;

	this.size += batch.size;

	this.tail = batch.tail;

	var sprite = batch.head;
	while(sprite)
	{
		sprite.batch = this;
		sprite = sprite.__next;
	}

}

/**
 * Grows the size of the batch. As the elements in the batch cannot have a dynamic size this function is used to increase the size of the batch. It also creates a little extra room so that the batch does not need to be resized every time a sprite is added
 * @methos growBatch
 */
PIXI.WebGLBatch.prototype.growBatch = function()
{
	var gl = this.gl;
	if( this.size == 1)
	{
		this.dynamicSize = 1;
	}
	else
	{
		this.dynamicSize = this.size * 1.5
	}
	// grow verts
	this.verticies = new Float32Array(this.dynamicSize * 8);

	gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
	gl.bufferData(gl.ARRAY_BUFFER,this.verticies , gl.DYNAMIC_DRAW);

	this.uvs  = new Float32Array( this.dynamicSize * 8 )
	gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
	gl.bufferData(gl.ARRAY_BUFFER, this.uvs , gl.DYNAMIC_DRAW);

	this.dirtyUVS = true;

	this.colors  = new Float32Array( this.dynamicSize * 4 )
	gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
	gl.bufferData(gl.ARRAY_BUFFER, this.colors , gl.DYNAMIC_DRAW);

	this.dirtyColors = true;

	this.indices = new Uint16Array(this.dynamicSize * 6);
	var length = this.indices.length/6;

	for (var i=0; i < length; i++)
	{
	    var index2 = i * 6;
	    var index3 = i * 4;
		this.indices[index2 + 0] = index3 + 0;
		this.indices[index2 + 1] = index3 + 1;
		this.indices[index2 + 2] = index3 + 2;
		this.indices[index2 + 3] = index3 + 0;
		this.indices[index2 + 4] = index3 + 2;
		this.indices[index2 + 5] = index3 + 3;
	};

	gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);

}

/**
 * Refresh's all the data in the batch and sync's it with the webGL buffers
 * @method refresh
 */
PIXI.WebGLBatch.prototype.refresh = function()
{
	var gl = this.gl;

	if (this.dynamicSize < this.size)
	{
		this.growBatch();
	}

	var indexRun = 0;
	var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index
	var a, b, c, d, tx, ty

	var displayObject = this.head

	while(displayObject)
	{
		index = indexRun * 8;

		var texture = displayObject.texture;

		var frame = texture.frame;
		var tw = texture.baseTexture.width;
		var th = texture.baseTexture.height;

		this.uvs[index + 0] = frame.x / tw;
		this.uvs[index +1] = frame.y / th;

		this.uvs[index +2] = (frame.x + frame.width) / tw;
		this.uvs[index +3] = frame.y / th;

		this.uvs[index +4] = (frame.x + frame.width) / tw;
		this.uvs[index +5] = (frame.y + frame.height) / th;

		this.uvs[index +6] = frame.x / tw;
		this.uvs[index +7] = (frame.y + frame.height) / th;

		displayObject.updateFrame = false;

		colorIndex = indexRun * 4;
		this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha;

		displayObject = displayObject.__next;

		indexRun ++;
	}

	this.dirtyUVS = true;
	this.dirtyColors = true;
}

/**
 * Updates all the relevant geometry and uploads the data to the GPU
 * @method update
 */
PIXI.WebGLBatch.prototype.update = function()
{
	var gl = this.gl;
	var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3

	var a, b, c, d, tx, ty;

	var indexRun = 0;

	var displayObject = this.head;

	while(displayObject)
	{
		width = displayObject.width;
		height = displayObject.height;

		aX = displayObject.anchor.x - displayObject.texture.trim.x
		aY = displayObject.anchor.y - displayObject.texture.trim.y
		w0 = width * (1-aX);
		w1 = width * -aX;

		h0 = height * (1-aY);
		h1 = height * -aY;

		index = indexRun * 8;

		worldTransform = displayObject.worldTransform;

		a = worldTransform[0];
		b = worldTransform[3];
		c = worldTransform[1];
		d = worldTransform[4];
		tx = worldTransform[2];
		ty = worldTransform[5];

		this.verticies[index + 0 ] = a * w1 + c * h1 + tx;
		this.verticies[index + 1 ] = d * h1 + b * w1 + ty;

		this.verticies[index + 2 ] = a * w0 + c * h1 + tx;
		this.verticies[index + 3 ] = d * h1 + b * w0 + ty;

		this.verticies[index + 4 ] = a * w0 + c * h0 + tx;
		this.verticies[index + 5 ] = d * h0 + b * w0 + ty;

		this.verticies[index + 6] =  a * w1 + c * h0 + tx;
		this.verticies[index + 7] =  d * h0 + b * w1 + ty;

		if(displayObject.updateFrame)
		{
			this.dirtyUVS = true;

			var texture = displayObject.texture;

			var frame = texture.frame;
			var tw = texture.baseTexture.width;
			var th = texture.baseTexture.height;

			this.uvs[index + 0] = frame.x / tw;
			this.uvs[index +1] = frame.y / th;

			this.uvs[index +2] = (frame.x + frame.width) / tw;
			this.uvs[index +3] = frame.y / th;

			this.uvs[index +4] = (frame.x + frame.width) / tw;
			this.uvs[index +5] = (frame.y + frame.height) / th;

			this.uvs[index +6] = frame.x / tw;
			this.uvs[index +7] = (frame.y + frame.height) / th;

			displayObject.updateFrame = false;
		}

		// TODO this probably could do with some optimisation....
		if(displayObject.cacheAlpha != displayObject.worldAlpha)
		{
			displayObject.cacheAlpha = displayObject.worldAlpha;

			var colorIndex = indexRun * 4;
			this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha;
			this.dirtyColors = true;
		}

		indexRun++;
		displayObject = displayObject.__next;
   }
}

/**
 * Draws the batch to the frame buffer
 * @method render
 */
PIXI.WebGLBatch.prototype.render = function()
{
	if(this.dirty)
	{
		this.refresh();
		this.dirty = false;
	}

	if (this.size == 0)return;

	this.update();
	var gl = this.gl;

	//TODO optimize this!
	if(this.blendMode == PIXI.blendModes.NORMAL)
	{
		gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
	}
	else
	{
		gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR);
	}

	var shaderProgram = PIXI.shaderProgram;

	// update the verts..
	gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
	// ok..
	gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verticies)
    gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0);

	// update the uvs
   	gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);

    if(this.dirtyUVS)
    {
    	this.dirtyUVS = false;
    	gl.bufferSubData(gl.ARRAY_BUFFER,  0, this.uvs);
    }

    gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);

    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, this.texture._glTexture);

	// update color!
	gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);

	if(this.dirtyColors)
    {
    	this.dirtyColors = false;
    	gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.colors);
	}

    gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0);

	// dont need to upload!
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);

    // DRAW THAT this!
    gl.drawElements(gl.TRIANGLES, this.size * 6, gl.UNSIGNED_SHORT, 0);
}

redpajama_set_name: RedPajamaGithub


text:
import { PlywoodValue } from '../datatypes/index';
import { SQLDialect } from '../dialect/baseDialect';

import { ChainableExpression, Expression, ExpressionJS, ExpressionValue } from './baseExpression';

export class NotExpression extends ChainableExpression {
  static op = 'Not';
  static fromJS(parameters: ExpressionJS): NotExpression {
    return new NotExpression(ChainableExpression.jsToValue(parameters));
  }

  constructor(parameters: ExpressionValue) {
    super(parameters, dummyObject);
    this._ensureOp('not');
    this._checkOperandTypes('BOOLEAN');
    this.type = 'BOOLEAN';
  }

  protected _calcChainableHelper(operandValue: any): PlywoodValue {
    return !operandValue;
  }

  protected _getSQLChainableHelper(dialect: SQLDialect, operandSQL: string): string {
    return `NOT(${operandSQL})`;
  }

  protected specialSimplify(): Expression {
    const { operand } = this;
    if (operand instanceof NotExpression) return operand.operand;
    return this;
  }
}

Expression.register(NotExpression);


text:
package strd.bytes;

import lmbrd.io.JVMReservedMemory;

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * User: light
 * Date: 7/16/13
 * Time: 6:30 PM
 */
public class BytesChannelWrapper implements InputBytes {

    private ByteBuffer buffer;

    public ByteBuffer getBuffer() {
        return buffer;
    }

    public BytesChannelWrapper(ByteBuffer buffer) {
        this.buffer = buffer;
    }

    public BytesChannelWrapper(byte[] byteArray) {
        this.buffer = ByteBuffer.wrap( byteArray );
    }

    @Override
    public long readLong() {
        return buffer.getLong();
    }

    @Override
    public byte[] readBytes(int size) {

        byte[] bytes = new byte[size];
        buffer.get(bytes);
        buffer.flip();
        return bytes;
    }

    @Override
    public int readUnsignedVarInt() {

        int value = 0;
        int i = 0;
        int b;

        int iters = 0;

        while (((b = read()) & 0x80) != 0) {
            // отсечка от бесконечного цикла на не правильном формате данных
            if (iters ++ > 128) throw new RuntimeException("Can not read varint");

            value |= (b & 0x7F) << i;
            i += 7;
        }

        return value | (b << i);
    }

    @Override
    public void skipBytes(int count) {
        buffer.position( buffer.position() + count );
    }

    @Override
    public int available() {
        return buffer.remaining();
    }

    @Override
    public int position() {
        return buffer.position();
    }

    @Override
    public void close() {
        JVMReservedMemory.cleanBuffer( buffer );
        this.buffer = null;
    }

    @Override
    public void readBytes(byte[] bytes) {
        buffer.get(bytes);
    }

    @Override
    public void readBytes(byte[] bytes, int off, int len) {
        buffer.get( bytes, off, len);
    }

    /**
     * @param bitLength a count of bits
     * @return the corresponding byte count padded to the next byte
     */
    public static int paddedByteCountFromBits(int bitLength) {
        return (bitLength + 7) / 8;
    }

    @Override
    public int readIntLittleEndianPaddedOnBitWidth(int bitWidth) throws IOException {
        int bytesWidth = paddedByteCountFromBits(bitWidth);
            switch (bytesWidth) {
                case 0:
                    return 0;
                case 1:
                    return readIntLittleEndianOnOneByte();
                case 2:
                    return readIntLittleEndianOnTwoBytes();
                case 3:
                    return readIntLittleEndianOnThreeBytes();
                case 4:
                    return readIntLittleEndian();
                default:
                    throw new IOException(
                            String.format("Encountered bitWidth (%d) that requires more than 4 bytes", bitWidth));
            }
    }

    /**
     * reads an int in little endian at the given position
     *
     * @param in
     * @param offset
     * @return
     * @throws IOException
     */
    public  int readIntLittleEndian(byte[] in, int offset) throws IOException {
        int ch4 = in[offset] & 0xff;
        int ch3 = in[offset + 1] & 0xff;
        int ch2 = in[offset + 2] & 0xff;
        int ch1 = in[offset + 3] & 0xff;
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

    public int readIntLittleEndian() throws IOException {
        // TODO: this is duplicated code in LittleEndianDataInputStream
        int ch1 = read();
        int ch2 = read();
        int ch3 = read();
        int ch4 = read();
        if ((ch1 | ch2 | ch3 | ch4) < 0) {
            throw new EOFException();
        }
        return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
    }

    public  int readIntLittleEndianOnOneByte() throws IOException {
        int ch1 = read();
        if (ch1 < 0) {
            throw new EOFException();
        }
        return ch1;
    }

    public  int readIntLittleEndianOnTwoBytes() throws IOException {
        int ch1 = read();
        int ch2 = read();
        if ((ch1 | ch2) < 0) {
            throw new EOFException();
        }
        return ((ch2 << 8) + (ch1 << 0));
    }

    public int read()  {
        return buffer.get() & 0xFF;
    }

    public  int readIntLittleEndianOnThreeBytes() throws IOException {
        int ch1 = read();
        int ch2 = read();
        int ch3 = read();
        if ((ch1 | ch2 | ch3) < 0) {
            throw new EOFException();
        }
        return ((ch3 << 16) + (ch2 << 8) + (ch1 << 0));
    }

    public  void writeIntLittleEndianOnOneByte( int v) throws IOException {
        buffer.put((byte) ((v >>> 0) & 0xFF));
    }

    public  void writeIntLittleEndianOnTwoBytes( int v) throws IOException {
        buffer.put((byte) ((v >>> 0) & 0xFF));
        buffer.put((byte) ((v >>> 8) & 0xFF));
    }

    public  void writeIntLittleEndianOnThreeBytes( int v) throws IOException {
        buffer.put((byte) ((v >>> 0) & 0xFF));
        buffer.put((byte) ((v >>> 8) & 0xFF));
        buffer.put((byte) ((v >>> 16) & 0xFF));
    }

    public  void writeIntLittleEndian( int v) throws IOException {
        // TODO: this is duplicated code in LittleEndianDataOutputStream
        buffer.put((byte) ((v >>> 0) & 0xFF));
        buffer.put((byte) ((v >>> 8) & 0xFF));
        buffer.put((byte) ((v >>> 16) & 0xFF));
        buffer.put((byte) ((v >>> 24) & 0xFF));
    }

    /**
     * Write a little endian int to out, using the the number of bytes required by
     * bit width
     */
    public  void writeIntLittleEndianPaddedOnBitWidth( int v, int bitWidth)
            throws IOException {

        int bytesWidth = paddedByteCountFromBits(bitWidth);
        switch (bytesWidth) {
            case 0:
                break;
            case 1:
                writeIntLittleEndianOnOneByte( v);
                break;
            case 2:
                writeIntLittleEndianOnTwoBytes( v);
                break;
            case 3:
                writeIntLittleEndianOnThreeBytes( v);
                break;
            case 4:
                writeIntLittleEndian( v);
                break;
            default:
                throw new IOException(
                        String.format("Encountered value (%d) that requires more than 4 bytes", v));
        }
    }

}


text:
package org.finos.waltz.service.changelog;

import org.finos.waltz.data.DBExecutorPoolInterface;
import org.finos.waltz.data.EntityReferenceNameResolver;
import org.finos.waltz.data.GenericSelector;
import org.finos.waltz.data.GenericSelectorFactory;
import org.finos.waltz.data.application.ApplicationDao;
import org.finos.waltz.data.changelog.ChangeLogDao;
import org.finos.waltz.data.changelog.ChangeLogSummariesDao;
import org.finos.waltz.data.logical_flow.LogicalFlowDao;
import org.finos.waltz.data.measurable_rating_planned_decommission.MeasurableRatingPlannedDecommissionDao;
import org.finos.waltz.data.measurable_rating_replacement.MeasurableRatingReplacementDao;
import org.finos.waltz.data.physical_flow.PhysicalFlowDao;
import org.finos.waltz.data.physical_specification.PhysicalSpecificationDao;
import org.finos.waltz.model.*;
import org.finos.waltz.model.changelog.ChangeLog;
import org.finos.waltz.model.changelog.ImmutableChangeLog;
import org.finos.waltz.model.external_identifier.ExternalIdValue;
import org.finos.waltz.model.logical_flow.LogicalFlow;
import org.finos.waltz.model.measurable_rating_planned_decommission.MeasurableRatingPlannedDecommission;
import org.finos.waltz.model.measurable_rating_replacement.MeasurableRatingReplacement;
import org.finos.waltz.model.physical_flow.PhysicalFlow;
import org.finos.waltz.model.physical_specification.PhysicalSpecification;
import org.finos.waltz.model.tally.DateTally;
import org.jooq.lambda.tuple.Tuple2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import static java.lang.String.format;
import static org.finos.waltz.common.Checks.checkNotEmpty;
import static org.finos.waltz.common.Checks.checkNotNull;
import static org.finos.waltz.common.SetUtilities.*;
import static org.finos.waltz.model.EntityKind.*;
import static org.finos.waltz.model.EntityReference.mkRef;
import static org.finos.waltz.model.EntityReferenceUtilities.safeName;
import static org.jooq.lambda.tuple.Tuple.tuple;

@Service
public class ChangeLogService {

    private final ChangeLogDao changeLogDao;
    private final ChangeLogSummariesDao changeLogSummariesDao;
    private final DBExecutorPoolInterface dbExecutorPool;
    private final PhysicalFlowDao physicalFlowDao;
    private final LogicalFlowDao logicalFlowDao;
    private final PhysicalSpecificationDao physicalSpecificationDao;
    private final ApplicationDao applicationDao;
    private final MeasurableRatingReplacementDao measurableRatingReplacementdao;
    private final MeasurableRatingPlannedDecommissionDao measurableRatingPlannedDecommissionDao;
    private final EntityReferenceNameResolver nameResolver;

    @Autowired
    public ChangeLogService(ChangeLogDao changeLogDao,
                            ChangeLogSummariesDao changeLogSummariesDao,
                            DBExecutorPoolInterface dbExecutorPool,
                            PhysicalFlowDao physicalFlowDao,
                            PhysicalSpecificationDao physicalSpecificationDao,
                            LogicalFlowDao logicalFlowDao,
                            ApplicationDao applicationDao,
                            MeasurableRatingReplacementDao measurableRatingReplacementDao,
                            MeasurableRatingPlannedDecommissionDao measurableRatingPlannedDecommissionDao,
                            EntityReferenceNameResolver nameResolver) {
        checkNotNull(changeLogDao, "changeLogDao must not be null");
        checkNotNull(changeLogSummariesDao, "changeLogSummariesDao must not be null");
        checkNotNull(dbExecutorPool, "dbExecutorPool cannot be null");
        checkNotNull(physicalFlowDao, "physicalFlowDao cannot be null");
        checkNotNull(physicalSpecificationDao, "physicalSpecificationDao cannot be null");
        checkNotNull(logicalFlowDao, "logicalFlowDao cannot be null");
        checkNotNull(measurableRatingReplacementDao, "measurableRatingReplacementDao cannot be null");
        checkNotNull(measurableRatingPlannedDecommissionDao, "measurableRatingPlannedDecommissionDao cannot be null");
        checkNotNull(nameResolver, "nameResolver cannot be null");

        this.changeLogDao = changeLogDao;
        this.changeLogSummariesDao = changeLogSummariesDao;
        this.dbExecutorPool = dbExecutorPool;
        this.physicalFlowDao = physicalFlowDao;
        this.physicalSpecificationDao = physicalSpecificationDao;
        this.logicalFlowDao = logicalFlowDao;
        this.applicationDao = applicationDao;
        this.measurableRatingReplacementdao = measurableRatingReplacementDao;
        this.measurableRatingPlannedDecommissionDao = measurableRatingPlannedDecommissionDao;
        this.nameResolver = nameResolver;
    }

    public List<ChangeLog> findByParentReferenceForDateRange(EntityReference ref,
                                                             Date startDate,
                                                             Date endDate,
                                                             Optional<Integer> limit) {
        checkNotNull(ref, "ref must not be null");
        return changeLogDao.findByParentReferenceForDateRange(ref, startDate, endDate, limit);
    }

    public List<ChangeLog> findByPersonReferenceForDateRange(EntityReference ref,
                                                             Date startDate,
                                                             Date endDate,
                                                             Optional<Integer> limit) {
        checkNotNull(ref, "ref must not be null");
        return changeLogDao.findByPersonReferenceForDateRange(ref, startDate, endDate, limit);
    }

    public List<ChangeLog> findByParentReference(EntityReference ref,
                                                 Optional<java.util.Date> date,
                                                 Optional<Integer> limit) {
        checkNotNull(ref, "ref must not be null");
        return changeLogDao.findByParentReference(ref, date, limit);
    }

    public List<ChangeLog> findByPersonReference(EntityReference ref,
                                                 Optional<java.util.Date> date,
                                                 Optional<Integer> limit) {
        checkNotNull(ref, "ref must not be null");
        return changeLogDao.findByPersonReference(ref, date, limit);
    }

    public List<ChangeLog> findByUser(String userName,
                                      Optional<Integer> limit) {
        checkNotEmpty(userName, "Username cannot be empty");
        return changeLogDao.findByUser(userName, limit);
    }

    public int write(ChangeLog changeLog) {
        return changeLogDao.write(changeLog);
    }

    public int[] write(Collection<ChangeLog> changeLogs) {
        return changeLogDao.write(changeLogs);
    }

    /**
     * Given an entity ref this function will determine all changelog entries made _after_ the latest
     * attestations for that entity.  Change log is matched between the attestation kind and the change
     * log child kind.
     *
     * @param ref  target reference
     * @return list of changes (empty if no attestations or if no changes)
     */
    public List<ChangeLog> findUnattestedChanges(EntityReference ref) {
        return changeLogDao.findUnattestedChanges(ref);
    }

    public void writeChangeLogEntries(EntityReference ref, String userId, String postamble, Operation operation) {
        switch (ref.kind()) {
            case PHYSICAL_FLOW:
                PhysicalFlow physicalFlow = physicalFlowDao.getById(ref.id());
                writeChangeLogEntries(physicalFlow, userId, postamble, operation);
                break;
            case PHYSICAL_SPECIFICATION:
                PhysicalSpecification physicalSpec = physicalSpecificationDao.getById(ref.id());
                writeChangeLogEntries(physicalSpec, userId, postamble, operation);
                break;
            case LOGICAL_DATA_FLOW:
                LogicalFlow logicalFlow = logicalFlowDao.getByFlowId(ref.id());
                writeChangeLogEntries(logicalFlow, userId, postamble, operation);
                break;
            case MEASURABLE_RATING_REPLACEMENT:
                MeasurableRatingReplacement measurableRatingReplacement = measurableRatingReplacementdao.getById(ref.id());
                writeChangeLogEntries(measurableRatingReplacement, userId, postamble, operation);
                break;
            case MEASURABLE_RATING_PLANNED_DECOMMISSION:
                MeasurableRatingPlannedDecommission measurableRatingPlannedDecommission = measurableRatingPlannedDecommissionDao.getById(ref.id());
                writeChangeLogEntries(measurableRatingPlannedDecommission, userId, postamble, operation);
            default:
                // nop
        }
    }

    public void writeChangeLogEntries(LogicalFlow logicalFlow,
                                      String userId,
                                      String postamble,
                                      Operation operation) {
        Tuple2<String, Set<EntityReference>> t = preparePreambleAndEntitiesForChangeLogs(logicalFlow);
        String message = format("%s: %s", t.v1, postamble);
        writeChangeLogEntries(t.v2, message, operation, LOGICAL_DATA_FLOW, userId);
    }

    public void writeChangeLogEntries(PhysicalFlow physicalFlow,
                                      String userId,
                                      String postamble,
                                      Operation operation) {
        Tuple2<String, Set<EntityReference>> t = preparePreambleAndEntitiesForChangeLogs(physicalFlow);
        String message = format("%s: %s", t.v1, postamble);
        writeChangeLogEntries(t.v2, message, operation, PHYSICAL_FLOW, userId);
    }

    public void writeChangeLogEntries(PhysicalSpecification physicalSpec,
                                      String userId,
                                      String postamble,
                                      Operation operation) {
        Tuple2<String, Set<EntityReference>> t = preparePreambleAndEntitiesForChangeLogs(physicalSpec);
        String message = format("%s: %s", t.v1, postamble);
        writeChangeLogEntries(t.v2, message, operation, PHYSICAL_FLOW, userId);
    }

    public void writeChangeLogEntries(MeasurableRatingReplacement measurableRatingReplacement,
                                      String userId,
                                      String postamble,
                                      Operation operation){
        Tuple2<String, Set<EntityReference>> t = preparePreambleAndEntitiesForChangeLogs(measurableRatingReplacement);
        String message = format("%s: %s", t.v1, postamble);
        writeChangeLogEntries(t.v2, message, operation, MEASURABLE_RATING_REPLACEMENT, userId);
    }

    public void writeChangeLogEntries(MeasurableRatingPlannedDecommission measurableRatingPlannedDecommission,
                                      String userId,
                                      String postamble,
                                      Operation operation){
        Tuple2<String, Set<EntityReference>> t = preparePreambleAndEntitiesForChangeLogs(measurableRatingPlannedDecommission);
        String message = format("%s: %s", t.v1, postamble);
        writeChangeLogEntries(t.v2, message, operation, MEASURABLE_RATING_PLANNED_DECOMMISSION, userId);
    }

    public List<DateTally> findCountByDateForParentKindBySelector(EntityKind parentKind,
                                                                  IdSelectionOptions selectionOptions,
                                                                  Optional<Integer> limit) {
        GenericSelector genericSelector = new GenericSelectorFactory().applyForKind(parentKind, selectionOptions);
        return changeLogSummariesDao.findCountByDateForParentKindBySelector(genericSelector, limit);
    }

    private void writeChangeLogEntries(Set<EntityReference> refs,
                                       String message,
                                       Operation operation,
                                       EntityKind childKind,
                                       String userId) {
        Set<ChangeLog> changeLogEntries = map(
                refs,
                r -> ImmutableChangeLog
                        .builder()
                        .parentReference(r)
                        .message(message)
                        .severity(Severity.INFORMATION)
                        .userId(userId)
                        .childKind(childKind)
                        .operation(operation)
                        .build());

        write(changeLogEntries);
    }

    private Tuple2<String, Set<EntityReference>> preparePreambleAndEntitiesForChangeLogs(PhysicalSpecification physicalSpec) {
        List<PhysicalFlow> physicalFlows = physicalFlowDao.findBySpecificationId(physicalSpec.id().get());

        String messagePreamble = format(
                "Physical spec: %s",
                physicalSpec.name());

        return tuple(
                messagePreamble,
                union(
                        map(physicalFlows, d -> d.entityReference()),
                        asSet(physicalSpec.entityReference())));

    }

    private Tuple2<String, Set<EntityReference>> preparePreambleAndEntitiesForChangeLogs(PhysicalFlow physicalFlow) {
        LogicalFlow logicalFlow = logicalFlowDao.getByFlowId(physicalFlow.logicalFlowId());
        PhysicalSpecification specification = physicalSpecificationDao.getById(physicalFlow.specificationId());

        String messagePreamble = format(
                "Physical flow: %s, from: %s, to: %s",
                specification.name(),
                safeName(logicalFlow.source()),
                safeName(logicalFlow.target()));

        return tuple(
                messagePreamble,
                asSet(
                        physicalFlow.entityReference(),
                        logicalFlow.entityReference(),
                        logicalFlow.source(),
                        logicalFlow.target()));

    }

    private Tuple2<String, Set<EntityReference>> preparePreambleAndEntitiesForChangeLogs(LogicalFlow logicalFlow) {
        String messagePreamble = format(
                "Logical flow from: %s, to: %s",
                safeName(logicalFlow.source()),
                safeName(logicalFlow.target()));

        return tuple(
                messagePreamble,
                asSet(
                        logicalFlow.entityReference(),
                        logicalFlow.source(),
                        logicalFlow.target()));
    }

    private Tuple2<String, Set<EntityReference>> preparePreambleAndEntitiesForChangeLogs(MeasurableRatingReplacement measurableRatingReplacement) {

        MeasurableRatingPlannedDecommission plannedDecommission = measurableRatingPlannedDecommissionDao.getById(measurableRatingReplacement.decommissionId());
        String measurableName = resolveName(plannedDecommission.measurableId(), MEASURABLE);
        String originalEntityName = resolveName(plannedDecommission.entityReference().id(), plannedDecommission.entityReference().kind());
        String newEntityName = resolveName(measurableRatingReplacement.entityReference().id(), measurableRatingReplacement.entityReference().kind());

        String messagePreamble = format(
                "Replacement %s: %s [%d], for measurable: %s [%d] on: %s [%d]",
                measurableRatingReplacement.entityReference().kind().name().toLowerCase(),
                newEntityName,
                measurableRatingReplacement.entityReference().id(),
                measurableName,
                plannedDecommission.measurableId(),
                originalEntityName,
                plannedDecommission.entityReference().id());

        return tuple(
                messagePreamble,
                asSet(measurableRatingReplacement.entityReference(), plannedDecommission.entityReference()));

    }

    private Tuple2<String, Set<EntityReference>> preparePreambleAndEntitiesForChangeLogs(MeasurableRatingPlannedDecommission measurableRatingPlannedDecommission) {

        Set<MeasurableRatingReplacement> replacements = measurableRatingReplacementdao.fetchByDecommissionId(measurableRatingPlannedDecommission.id());
        String measurableName = resolveName(measurableRatingPlannedDecommission.measurableId(), MEASURABLE);
        EntityReference entityReference = measurableRatingPlannedDecommission.entityReference();
        String entityName = resolveName(entityReference.id(), entityReference.kind());

        String messagePreamble = format(
                "Measurable Rating: %s [%d] on: %s [%s]",
                measurableName,
                measurableRatingPlannedDecommission.measurableId(),
                entityName,
                getExternalId(entityReference)
                        .map(ExternalIdValue::value)
                        .orElse(String.valueOf(entityReference.id())));

        return tuple(
                messagePreamble,
                union(map(replacements, MeasurableRatingReplacement::entityReference), asSet(entityReference)));
    }

    private Optional<ExternalIdValue> getExternalId(EntityReference entityReference) {
        return entityReference.kind().equals(APPLICATION)
                ? applicationDao.getById(entityReference.id()).assetCode()
                : Optional.empty();
    }

    private String resolveName(long id, EntityKind kind) {
        return nameResolver
                .resolve(mkRef(kind, id))
                .flatMap(EntityReference::name)
                .orElse("UNKNOWN");
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.nise.ux.asl.run (Unnamed - org.nise.ux:abstract-service-library:jar:2.5.3-java6 2.5.3-java6 API)</title>
<meta name="date" content="2014-02-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.nise.ux.asl.run

Classes

ParallelServiceClient

RetryingParallelClient

SequentialServiceClient

ServiceServerBuilder

ServiceServerImpl


text:
package chord.analyses.point;

import joeq.Class.jq_Class;
import joeq.Class.jq_Method;
import joeq.Compiler.Quad.EntryOrExitBasicBlock;
import joeq.Compiler.Quad.ControlFlowGraph;
import chord.program.visitors.IMethodVisitor;
import chord.project.Chord;
import chord.project.analyses.ProgramRel;

/**
 * Relation containing each tuple (m,p) such that statement p is
 * the unique entry basic block of method m.
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
@Chord(
	name = "MPhead",
	sign = "M0,P0:M0xP0"
)
public class RelMPhead extends ProgramRel
		implements IMethodVisitor {
	public void visit(jq_Class c) { }
	public void visit(jq_Method m) {
		if (m.isAbstract())
			return;
		ControlFlowGraph cfg = m.getCFG();
		EntryOrExitBasicBlock be = cfg.entry();
		add(m, be);
	}
}


text:
<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class DWEmailVerifyShortcode{

	/**
	 * Check validation status
	 */
	public $validation_status = '';

	/**
	 * $shortcode_tag
	 * holds the name of the shortcode tag
	 * @var string
	 */
	public $shortcode_tag = 'dw-verify-email';

	/**
	 * $token_cookie_name
	 * holds the name of the verify token cookie
	 * @var string
	 */
	public $token_cookie_name = 'dw_verify_token';

	/**
	 * $cookie_path
	 * holds the path of the token cookie. MUST be the same when setting and unsetting the cookie, or else it won't be unset properly
	 * @var string
	 */
	public $cookie_path = '/';

	/**
	 * __construct
	 * class constructor will set the needed filter and action hooks
	 *
	 */
	function __construct(){
		//add shortcode
		add_shortcode( $this->shortcode_tag, [$this, 'shortcode_handler'] );
		add_action( 'wp', [$this, 'verify_stuff'] );
	}

	public function verify_stuff(){
		if( ! is_page( get_option('dw_verify_authorize_page') ) ) return;

		/**
		 * This page strips the verification token from the URL and redirects back to itself, to guard against referrer leakage
		 * See https://security.stackexchange.com/a/117871
		*/

		$user_id = absint( $_GET['user_id'] );

		if( empty( $_GET['user_id'] ) || ! DWEmailVerify::instance()->needs_validation( $user_id ) ) {
			$this->validation_status = 'invalid_request';
			return;
		}

		// Check if URL contains verification token
		if( empty( $_GET['verify_email'] ) || ! preg_match( '/^[a-f0-9]{32}$/', $_GET['verify_email'] ) ) {
			// If it *doesn't*, check for it in a cookie
			if( ! isset( $_COOKIE[ $this->token_cookie_name ] ) ) {
				// If it isn't there, validation attempt has failed
				$this->validation_status = 'invalid_request';
				return;
			}
		} else {
			// If it does, store it in a cookie and redirect back here, stripping token from URL in process
			setcookie( $this->token_cookie_name, $_GET[ 'verify_email' ], time() + 120, $this->cookie_path );
			$redirect_to = add_query_arg( array(
				'user_id' => $user_id
			), get_permalink( get_option( 'dw_verify_authorize_page' ) ) );
			wp_safe_redirect( $redirect_to );
			exit;
		}

		// If we get this far, we've found the token in a cookie. Unset the cookie first, then attempt to validate the token
		$token = $_COOKIE[ $this->token_cookie_name ];
		unset( $_COOKIE[ $this->token_cookie_name ] );
		setcookie( $this->token_cookie_name, '', time() - 3600, $this->cookie_path ); // cookie path must be included and match what was set or it won't delete
		if( DWEmailVerify::instance()->verify_if_valid( $token, $user_id ) ) {
			$this->validation_status = 'validated';

			add_action( 'wp_head', [$this, 'page_redirect'] );

		} else {
			$this->validation_status = 'invalid_hash';
		}
	}

	/**
	 * Redirect page
	 */
	public function page_redirect(){
		if( $redirect = DWEmailVerify::instance()->redirect_url() ) {
			echo '<meta http-equiv="refresh" content="5;url='. $redirect .'" />';
		}
	}

	/**
	 * shortcode_handler
	 * @param  array  $atts shortcode attributes
	 * @param  string $content shortcode content
	 * @return string
	 */
	function shortcode_handler( $atts, $content = null ) {
		$output = '';

		if( ! empty( $_GET['awaiting-verification'] ) && 'true' == $_GET['awaiting-verification'] ) {
			return __('You have successfully registered on our website, Please check your email and click on the link we sent you to verify your email address.', 'dwverify');
		}

		switch ( $this->validation_status ) {
			case 'invalid_request':
				$output .= __('Invalid request', 'dwverify');
				break;

			case 'validated' :
				$output .= sprintf( __('Your email has been verified, you will be redirected in a few seconds click here if your browser does not redirect you automatically.', 'dwverify'), DWEmailVerify::instance()->redirect_url() );
				break;

			case 'invalid_hash':
				$output .= __('Sorry we could not verify your email address.', 'dwverify');
				break;
		}

		return $output;
	}
}

new DWEmailVerifyShortcode();


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.internal.util.privilegedactions;

import java.security.PrivilegedAction;

/**
 * Checks if an external class is present in the provided class loader.
 */
public final class IsClassPresent implements PrivilegedAction<Boolean> {

	private final String className;

	private final ClassLoader classLoader;

	public static IsClassPresent action(String className, ClassLoader classLoader) {
		return new IsClassPresent( className, classLoader );
	}

	private IsClassPresent(String className, ClassLoader classLoader) {
		this.className = className;
		this.classLoader = classLoader;
	}

	@Override
	public Boolean run() {
		try {
			Class.forName( className, false, classLoader );
			return Boolean.TRUE;
		}
		catch (ClassNotFoundException e) {
			return Boolean.FALSE;
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Encyclop. Mycol. 1: 330 (1934)

#### Original name
Inocybe friesii f. laricina R. Heim

### Remarks
null


text:
import React from 'react'

const BannerRules = () => {
  return (

"Make the Rules"

leave notes for your flatmates,
 get the most of your sharing space

  )
}

export default BannerRules


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on Jan 19, 2008
 */
package org.globus.cog.abstraction.coaster.service.local;

import org.globus.cog.abstraction.coaster.rlog.RemoteLogCommand;
import org.globus.cog.abstraction.coaster.rlog.RemoteLogHandler;
import org.globus.cog.abstraction.coaster.service.ResourceUpdateCommand;
import org.globus.cog.abstraction.coaster.service.ResourceUpdateHandler;
import org.globus.cog.abstraction.coaster.service.job.manager.BQPStatusHandler;
import org.globus.cog.abstraction.coaster.service.job.manager.ServiceShutdownNotificationHandler;
import org.globus.cog.abstraction.impl.file.coaster.handlers.GetFileHandler;
import org.globus.cog.abstraction.impl.file.coaster.handlers.PutFileHandler;
import org.globus.cog.coaster.AbstractRequestManager;
import org.globus.cog.coaster.handlers.ChannelConfigurationHandler;
import org.globus.cog.coaster.handlers.HeartBeatHandler;

public class LocalRequestManager extends AbstractRequestManager {
    public static final LocalRequestManager INSTANCE = new LocalRequestManager();

    public LocalRequestManager() {
        addHandler(VersionHandler.NAME, VersionHandler.class);
        addHandler(RegistrationHandler.NAME, RegistrationHandler.class);
        addHandler(UnregisterHandler.NAME, UnregisterHandler.class);
        addHandler(JobStatusHandler.NAME, JobStatusHandler.class);
        addHandler(HeartBeatHandler.NAME, HeartBeatHandler.class);
        addHandler(BQPStatusHandler.NAME, BQPStatusHandler.class);
        addHandler(RemoteLogCommand.NAME, RemoteLogHandler.class);
        addHandler("GET", GetFileHandler.class);
        addHandler("PUT", PutFileHandler.class);
        addHandler(ResourceUpdateCommand.NAME, ResourceUpdateHandler.class);
        addHandler(ChannelConfigurationHandler.NAME, ChannelConfigurationHandler.class);
        addHandler("SHUTDOWN", ServiceShutdownNotificationHandler.class);
    }
}


text:
package liquibase.datatype.core;

import java.math.BigInteger;
import java.util.Arrays;

import liquibase.database.Database;
import liquibase.database.core.HsqlDatabase;
import liquibase.database.core.InformixDatabase;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
import liquibase.exception.DatabaseException;

@DataTypeInfo(name="varchar", aliases = {"java.sql.Types.VARCHAR", "java.lang.String", "varchar2", "character varying"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class VarcharType extends CharType {

    @Override
    public DatabaseDataType toDatabaseDataType(Database database) {
        if (database instanceof OracleDatabase
                || (database instanceof HsqlDatabase && ((HsqlDatabase) database).isUsingOracleSyntax())) {
            return new DatabaseDataType("VARCHAR2", getParameters());
        }

        if (database instanceof InformixDatabase && getSize() > 255) {
            return new DatabaseDataType("LVARCHAR", getParameters());
        }

        if (database instanceof MSSQLDatabase) {
            Object[] parameters = getParameters();
            if (parameters.length > 0) {
                String param1 = parameters[0].toString();
                if (!param1.matches("\\d+")
                        || new BigInteger(param1).compareTo(BigInteger.valueOf(8000L)) > 0) {

                    try {
                        if (database.getDatabaseMajorVersion() <= 8) { //2000 or earlier
                            return new DatabaseDataType(database.escapeDataTypeName("varchar"), "8000");
                        }
                    } catch (DatabaseException ignore) { } //assuming it is a newer version

                    DatabaseDataType type = new DatabaseDataType(database.escapeDataTypeName("varchar"), "MAX");
                    type.addAdditionalInformation(getAdditionalInformation());
                    return type;
                }
            }
            if (parameters.length == 0) {
                parameters = new Object[] { 1 };
            } else if (parameters.length > 1) {
                parameters = Arrays.copyOfRange(parameters, 0, 1);
            }
            DatabaseDataType type = new DatabaseDataType(database.escapeDataTypeName("varchar"), parameters);
            type.addAdditionalInformation(getAdditionalInformation());
            return type;
        }

        return super.toDatabaseDataType(database);
    }

    //oracle
    //			if (columnTypeString.toUpperCase().startsWith("VARCHAR2")) {
//				// Varchar2 type pattern: VARCHAR2(50 BYTE) | VARCHAR2(50 CHAR)
//				returnTypeName = getVarcharType();
//				if (precision != null) {
//					String[] typeParams = precision.split(" ");
//					returnTypeName.setFirstParameter(typeParams[0].trim());
//					if (typeParams.length > 1) {
//						returnTypeName.setUnit(typeParams[1]);
//					}
//				}
//			} else if (columnTypeString.toUpperCase().startsWith("NVARCHAR2")) {
//				// NVarchar2 type pattern: VARCHAR2(50 BYTE) | VARCHAR2(50 CHAR)
//				returnTypeName = getNVarcharType();
//				if (precision != null) {
//					String[] typeParams = precision.split(" ");
//					returnTypeName.setFirstParameter(typeParams[0].trim());
//					if (typeParams.length > 1) {
//						returnTypeName.setUnit(typeParams[1]);
//					}
//				}
//			}

}


text:
/* ******************************************************************
***********************************
*** Natural: A remote desktop for embed systems.
*** By Alejandro Linarez Rangel.
*** Manages UNIX groups and users.
***********************************
****************************************************************** */

/***************************************************************************
Copyright 2016 Alejandro Linarez Rangel

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/

var fs = require("fs");

/*
Devuelve el nombre de usuario del userid especificado.
Para ello el lee /etc/passwd
*/
function GetUsernameFromUserID(userid)
{
	var etcpasswd = fs.readFileSync("/etc/passwd", "utf8");
	var lines = etcpasswd.split("\n");
	var i = 0;
	var j = 0;
	var s1 = lines.length;
	for(i = 0; i < s1; i++)
	{
		var line = lines[i].split(":");
		if(line[2] == userid)
		{
			return line[0];
		}
	}
	return "";
}

/*
Devuelve el nombre real del usuario con el userid especificado.
Para ello el lee /etc/passwd
*/
function GetUserlongFromUserID(userid)
{
	var etcpasswd = fs.readFileSync("/etc/passwd", "utf8");
	var lines = etcpasswd.split("\n");
	var i = 0;
	var j = 0;
	var s1 = lines.length;
	for(i = 0; i < s1; i++)
	{
		var line = lines[i].split(":");
		if(line[2] == userid)
		{
			return line[4].split(",")[0];
		}
	}
	return "";
}

/*
Devuelve el nombre real del usuario con el username especificado.
Para ello el lee /etc/passwd
*/
function GetUserlongFromUserName(username)
{
	var etcpasswd = fs.readFileSync("/etc/passwd", "utf8");
	var lines = etcpasswd.split("\n");
	var i = 0;
	var j = 0;
	var s1 = lines.length;
	for(i = 0; i < s1; i++)
	{
		var line = lines[i].split(":");
		if(line[0] == username)
		{
			return line[4].split(",")[0];
		}
	}
	return "";
}

/*
Devuelve el nombre de un grupo en base a su groupid
*/
function GetGroupnameFromGroupID(groupid)
{
	var etcgroup = fs.readFileSync("/etc/group", "utf8");
	var lines = etcgroup.split("\n");
	var i = 0;
	var j = 0;
	var s1 = lines.length;
	for(i = 0; i < s1; i++)
	{
		var line = lines[i].split(":");
		if(line[2] == groupid)
		{
			return line[0];
		}
	}
	return "";
}

/*
Determina si el usuario user esta en el grupo group.
callback es de la forma (err, bool is_in_group) => void
*/
function IsUserInGroup(user, group, callback)
{
	fs.readFile("/etc/group", "utf8", function(err, data)
	{
		if(err)
		{
			console.error(err);
			callback(err);
			return;
		}
		var lines = data.split("\n");
		var i = 0;
		var j = lines.length;
		for(i = 0; i < j; i++)
		{
			var line = lines[i];
			var fl = line.split(":");
			var groupname = fl[0];
			if(groupname == group)
			{
				var users = fl[3].split(",");
				var w = 0;
				var t = users.length;
				for(w = 0; w < t; w++)
				{
					var cuser = users[w];
					if(cuser == user)
					{
						callback(null, true); // Se encontro el usuario y si esta en el grupo
						return;
					}
				}
				callback(null, false); // Se encontro el grupo, pero el usuario no estaba alli
				return;
			}
		}
		callback(null, false); // No se encontro el grupo
	});
}

/*
Determina si el usuario username puede realizar la accion d en el directorio o archivo dirorfile.
callback es de la forma (err, bool the_user_can) => void
*/
function UserCan(d, username, dirorfile, callback)
{
	var useregex = /^[a-z][a-zA-Z0-9_\-]*$/g;
	username = username.toString() + "";
	if(username.match(useregex) == null)
	{
		console.error("The user not match the uregex");
		callback(new Error("The user not match the uregex"));
		return;
	}
	var dirgroup = fs.stat(dirorfile, function(err, stats)
	{
		if(err)
		{
			console.error(err);
			callback(err);
			return;
		}
		d = 0 + d;
		var ownerCan = stats["mode"] & (d * 64);
		var groupCan = stats["mode"] & (d * 8);
		var othersCan = stats["mode"] & d;
		var gid = stats["gid"];
		var uid = stats["uid"];
		console.log("Group: I can do " + d);
		if(username == GetUsernameFromUserID(uid))
		{
			console.log("I am the owner: " + (ownerCan));
			// I am the owner
			callback(null, ownerCan);
			return;
		}
		IsUserInGroup(username, GetGroupnameFromGroupID(gid), function(err, isin)
		{
			if(err)
			{
				console.error(err);
				callback(err);
				return;
			}
			// I am in the groud
			if(isin)
			{
				console.log("I am in the group: " + (ownerCan));
				callback(null, groupCan);
			}
			else
			{
				console.log("Anybody else can: " + (ownerCan));
				// Any can
				callback(null, othersCan);
			}
		})
	});
}

/*
Determina si el usuario puede leer un archivo o directorio.
Equivalente a UseCan(4, username, dirorfile, callback)
*/
function UserCanRead(username, dirorfile, callback)
{
	UserCan(4, username, dirorfile, callback)
}

/*
Determina si el usuario puede escribir en un archivo o directorio.
Equivalente a UseCan(2, username, dirorfile, callback)
*/
function UserCanWrite(username, dirorfile, callback)
{
	UserCan(2, username, dirorfile, callback)
}

/*
Determina si el usuario puede ejecutar un archivo o directorio.
Equivalente a UseCan(1, username, dirorfile, callback)
*/
function UserCanExec(username, dirorfile, callback)
{
	UserCan(1, username, dirorfile, callback)
}

module.exports = {
	GetUsernameFromUserID: GetUsernameFromUserID,
	GetGroupnameFromGroupID: GetGroupnameFromGroupID,
	GetUserlongFromUserName: GetUserlongFromUserName,
	GetUserlongFromUserID: GetUserlongFromUserID,
	IsUserInGroup: IsUserInGroup,
	UserCan: UserCan,
	UserCanWrite: UserCanWrite,
	UserCanRead: UserCanRead,
	UserCanExec: UserCanExec
};