text:
package se.sics.cooja.contikimote;

import java.awt.Container;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Random;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JComponent;
import javax.swing.JLabel;

import org.apache.log4j.Logger;
import org.jdom.Element;

import se.sics.cooja.AbstractionLevelDescription;
import se.sics.cooja.ClassDescription;
import se.sics.cooja.CoreComm;
import se.sics.cooja.GUI;
import se.sics.cooja.Mote;
import se.sics.cooja.MoteInterface;
import se.sics.cooja.MoteType;
import se.sics.cooja.ProjectConfig;
import se.sics.cooja.SectionMoteMemory;
import se.sics.cooja.Simulation;
import se.sics.cooja.dialogs.CompileContiki;
import se.sics.cooja.dialogs.ContikiMoteCompileDialog;
import se.sics.cooja.dialogs.MessageList;
import se.sics.cooja.dialogs.MessageList.MessageContainer;
import se.sics.cooja.util.StringUtils;

/**
 * The Cooja mote type holds the native library used to communicate with an
 * underlying Contiki system. All communication with that system should always
 * pass through this mote type.
 *

 * This type also contains information about sensors and mote interfaces a mote
 * of this type has.
 *

 * All core communication with the Cooja mote should be via this class. When a
 * mote type is created it allocates a CoreComm to be used with this type, and
 * loads the variable and segments addresses.
 *

 * When a new mote type is created an initialization function is run on the
 * Contiki system in order to create the initial memory. When a new mote is
 * created the createInitialMemory() method should be called to get this initial
 * memory for the mote.
 *
 * @author Fredrik Osterlind
 */
@ClassDescription("Cooja mote")
@AbstractionLevelDescription("OS level")
public class ContikiMoteType implements MoteType {
  private static Logger logger = Logger.getLogger(ContikiMoteType.class);

  public static final String ID_PREFIX = "mtype";

  /**
   * Library file suffix
   */
  final static public String librarySuffix = ".cooja";

  /**
   * Map file suffix
   */
  final static public String mapSuffix = ".map";

  /**
   * Make archive file suffix
   */
  final static public String dependSuffix = ".a";

  /**
   * Temporary output directory
   */
  final static public File tempOutputDirectory = new File("obj_cooja");

  /**
   * Communication stacks in Contiki.
   */
  public enum NetworkStack {
    DEFAULT, MANUAL;
    public String manualHeader = "netstack-conf-example.h";

    public String toString() {
      if (this == DEFAULT) {
        return "Default (from contiki-conf.h)";
      } else if (this == MANUAL) {
        return "Manual netstack header";
      }
      return "[unknown]";
    }

    public String getHeaderFile() {
      if (this == DEFAULT) {
        return null;
      } else if (this == MANUAL) {
        return manualHeader;
      }
      return null;
    }

    public String getConfig() {
      if (this == DEFAULT) {
        return "DEFAULT";
      } else if (this == MANUAL) {
        return "MANUAL:" + manualHeader;
      }
      return "[unknown]";
    }

    public static NetworkStack parseConfig(String config) {
      if (config.equals("DEFAULT")) {
        return DEFAULT;
      } else if (config.startsWith("MANUAL")) {
        NetworkStack st = MANUAL;
        st.manualHeader = config.split(":")[1];
        return st;
      }

      /* TODO Backwards compatibility */
      logger.warn("Bad network stack config: '" + config + "', using default");
      return DEFAULT;
    }
  }

  private final String[] sensors = { "button_sensor", "pir_sensor", "vib_sensor" };

  private String identifier = null;
  private String description = null;
  private File fileSource = null;
  private File fileFirmware = null;
  private String compileCommands = null;

  /* For internal use only: using during Contiki compilation. */
  private File contikiApp = null; /* Contiki application: hello-world.c */
  public File libSource = null; /* JNI library: obj_cooja/mtype1.c */
  public File libFile = null; /* JNI library: obj_cooja/mtype1.lib */
  public File archiveFile = null; /* Contiki archive: obj_cooja/mtype1.a */
  public File mapFile = null; /* Contiki map: obj_cooja/mtype1.map */
  public String javaClassName = null; /* Loading Java class name: Lib1 */

  private String[] coreInterfaces = null;

  private ArrayList<Class<? extends MoteInterface>> moteInterfacesClasses = null;

  private boolean hasSystemSymbols = false;

  private NetworkStack netStack = NetworkStack.DEFAULT;

  // Type specific class configuration
  private ProjectConfig myConfig = null;

  private CoreComm myCoreComm = null;

  // Initial memory for all motes of this type
  private SectionMoteMemory initialMemory = null;

  /**
   * Creates a new uninitialized Cooja mote type. This mote type needs to load
   * a library file and parse a map file before it can be used.
   */
  public ContikiMoteType() {
  }

  public Mote generateMote(Simulation simulation) {
    return new ContikiMote(this, simulation);
  }

  public boolean configureAndInit(Container parentContainer, Simulation simulation,
      boolean visAvailable) throws MoteTypeCreationException {
    myConfig = simulation.getGUI().getProjectConfig().clone();

    if (visAvailable) {

      if (getDescription() == null) {
        setDescription("Cooja Mote Type #" + (simulation.getMoteTypes().length+1));
      }

      /* Compile Contiki from dialog */
      boolean compileOK =
        ContikiMoteCompileDialog.showDialog(parentContainer, simulation, this);
      if (!compileOK) {
        return false;
      }

    } else {
      if (getIdentifier() == null) {
        throw new MoteTypeCreationException("No identifier specified");
      }
      if (getContikiSourceFile() == null) {
        throw new MoteTypeCreationException("No Contiki application specified");
      }

      /* Create variables used for compiling Contiki */
      contikiApp = getContikiSourceFile();
      libSource = new File(
          contikiApp.getParentFile(),
          "obj_cooja/" + getIdentifier() + ".c");
      libFile = new File(
          contikiApp.getParentFile(),
          "obj_cooja/" + getIdentifier() + librarySuffix);
      archiveFile = new File(
          contikiApp.getParentFile(),
          "obj_cooja/" + getIdentifier() + dependSuffix);
      mapFile = new File(
          contikiApp.getParentFile(),
          "obj_cooja/" + getIdentifier() + mapSuffix);
      javaClassName = CoreComm.getAvailableClassName();

      if (javaClassName == null) {
        throw new MoteTypeCreationException("Could not allocate a core communicator.");
      }

      /* Delete output files */
      libSource.delete();
      libFile.delete();
      archiveFile.delete();
      mapFile.delete();

      /* Generate Contiki main source */
      /*try {
        CompileContiki.generateSourceFile(
            libSource,
            javaClassName,
            getSensors(),
            getCoreInterfaces()
        );
      } catch (Exception e) {
        throw (MoteTypeCreationException) new MoteTypeCreationException(
        "Error when generating Contiki main source").initCause(e);
      }*/

      /* Prepare compiler environment */
      String[][] env;
      try {
        env = CompileContiki.createCompilationEnvironment(
            getIdentifier(),
            contikiApp,
            mapFile,
            libFile,
            archiveFile,
            javaClassName);
        CompileContiki.redefineCOOJASources(
        		this,
        		env
        );
      } catch (Exception e) {
        throw (MoteTypeCreationException) new MoteTypeCreationException(
            "Error when creating environment: " + e.getMessage()).initCause(e);
      }
      String[] envOneDimension = new String[env.length];
      for (int i=0; i < env.length; i++) {
        envOneDimension[i] = env[i][0] + "=" + env[i][1];
      }

      /* Compile Contiki (may consist of several commands) */
      if (getCompileCommands() == null) {
        throw new MoteTypeCreationException("No compile commands specified");
      }
      final MessageList compilationOutput = new MessageList();
      String[] arr = getCompileCommands().split("\n");
      for (String cmd: arr) {
        if (cmd.trim().isEmpty()) {
          continue;
        }

        try {
          CompileContiki.compile(
              cmd,
              envOneDimension,
              null /* Do not observe output firmware file */,
              getContikiSourceFile().getParentFile(),
              null,
              null,
              compilationOutput,
              true
          );
        } catch (Exception e) {
          MoteTypeCreationException newException =
            new MoteTypeCreationException("Mote type creation failed: " + e.getMessage());
          newException = (MoteTypeCreationException) newException.initCause(e);
          newException.setCompilationOutput(compilationOutput);

          /* Print last 10 compilation errors to console */
          MessageContainer[] messages = compilationOutput.getMessages();
          for (int i=messages.length-10; i < messages.length; i++) {
            if (i < 0) {
              continue;
            }
            logger.fatal(">> " + messages[i]);
          }

          logger.fatal("Compilation error: " + e.getMessage());
          throw newException;
        }
      }

      /* Make sure compiled firmware exists */
      if (getContikiFirmwareFile() == null ||
          !getContikiFirmwareFile().exists()) {
        throw new MoteTypeCreationException("Contiki firmware file does not exist: " + getContikiFirmwareFile());
      }
    }

    /* Load compiled library */
    doInit();
    return true;
  }

  public static File getExpectedFirmwareFile(File source) {
    File parentDir = source.getParentFile();
    String sourceNoExtension = source.getName().substring(0, source.getName().length()-2);

    return new File(parentDir, sourceNoExtension + librarySuffix);
  }

  /**
   * For internal use.
   *
   * This method creates a core communicator linking a Contiki library and a Java class.
   * It furthermore parses library Contiki memory addresses and creates the initial memory.
   *
   * @throws MoteTypeCreationException
   */
  private void doInit() throws MoteTypeCreationException {

    if (myCoreComm != null) {
      throw new MoteTypeCreationException(
          "Core communicator already used: " + myCoreComm.getClass().getName());
    }

    if (getContikiFirmwareFile() == null ||
        !getContikiFirmwareFile().exists()) {
      throw new MoteTypeCreationException("Library file could not be found: " + getContikiFirmwareFile());
    }

    if (this.javaClassName == null) {
      throw new MoteTypeCreationException("Unknown Java class library: " + this.javaClassName);
    }

    // Allocate core communicator class
    logger.info("Creating core communicator between Java class '" + javaClassName + "' and Contiki library '" + getContikiFirmwareFile().getName() + "'");
    myCoreComm = CoreComm.createCoreComm(this.javaClassName, getContikiFirmwareFile());

    /* Parse addresses using map file or command */
    boolean useCommand = Boolean.parseBoolean(GUI.getExternalToolsSetting("PARSE_WITH_COMMAND", "false"));

    int dataSectionAddr = -1, dataSectionSize = -1;
    int bssSectionAddr = -1, bssSectionSize = -1;
    int commonSectionAddr = -1, commonSectionSize = -1;
    int readonlySectionAddr = -1, readonlySectionSize = -1;

    HashMap<String, Integer> addresses = new HashMap<String, Integer>();
    if (useCommand) {
      /* Parse command output */
      String[] output = loadCommandData(getContikiFirmwareFile());
      if (output == null) {
        throw new MoteTypeCreationException("No parse command output loaded");
      }
      boolean parseOK = parseCommandData(output, addresses);
      if (!parseOK) {
        logger.fatal("Command output parsing failed");
        throw new MoteTypeCreationException("Command output parsing failed");
      }

      dataSectionAddr = parseCommandDataSectionAddr(output);
      dataSectionSize = parseCommandDataSectionSize(output);
      bssSectionAddr = parseCommandBssSectionAddr(output);
      bssSectionSize = parseCommandBssSectionSize(output);
      commonSectionAddr = parseCommandCommonSectionAddr(output);
      commonSectionSize = parseCommandCommonSectionSize(output);

      try {
        readonlySectionAddr = parseCommandReadonlySectionAddr(output);
        readonlySectionSize = parseCommandReadonlySectionSize(output);
      } catch (Exception e) {
        readonlySectionAddr = -1;
        readonlySectionSize = -1;
      }

    } else {
      /* Parse command output */
      if (mapFile == null ||
          !mapFile.exists()) {
        throw new MoteTypeCreationException("Map file " + mapFile + " could not be found");
      }
      String[] mapData = loadMapFile(mapFile);
      if (mapData == null) {
        logger.fatal("No map data could be loaded");
        throw new MoteTypeCreationException("No map data could be loaded: " + mapFile);
      }
      boolean parseOK = parseMapFileData(mapData, addresses);
      if (!parseOK) {
        logger.fatal("Map data parsing failed");
        throw new MoteTypeCreationException("Map data parsing failed: " + mapFile);
      }

      dataSectionAddr = parseMapDataSectionAddr(mapData);
      dataSectionSize = parseMapDataSectionSize(mapData);
      bssSectionAddr = parseMapBssSectionAddr(mapData);
      bssSectionSize = parseMapBssSectionSize(mapData);
      commonSectionAddr = parseMapCommonSectionAddr(mapData);
      commonSectionSize = parseMapCommonSectionSize(mapData);
      readonlySectionAddr = -1;
      readonlySectionSize = -1;

    }

    if (dataSectionAddr >= 0) {
      logger.info(getContikiFirmwareFile().getName() +
          ": data section at 0x" + Integer.toHexString(dataSectionAddr) +
          " (" + dataSectionSize + " == 0x" + Integer.toHexString(dataSectionSize) + " bytes)");
    } else {
      logger.fatal(getContikiFirmwareFile().getName() + ": no data section found");
    }
    if (bssSectionAddr >= 0) {
      logger.info(getContikiFirmwareFile().getName() +
          ": BSS section at 0x" + Integer.toHexString(bssSectionAddr) +
          " (" + bssSectionSize + " == 0x" + Integer.toHexString(bssSectionSize) + " bytes)");
    } else {
      logger.fatal(getContikiFirmwareFile().getName() + ": no BSS section found");
    }
    if (commonSectionAddr >= 0) {
      logger.info(getContikiFirmwareFile().getName() +
          ": common section at 0x" + Integer.toHexString(commonSectionAddr) +
          " (" + commonSectionSize + " == 0x" + Integer.toHexString(commonSectionSize) + " bytes)");
    } else {
      logger.info(getContikiFirmwareFile().getName() + ": no common section found");
    }
    if (readonlySectionAddr >= 0) {
      logger.info(getContikiFirmwareFile().getName() +
          ": readonly section at 0x" + Integer.toHexString(readonlySectionAddr) +
          " (" + readonlySectionSize + " == 0x" + Integer.toHexString(readonlySectionSize) + " bytes)");
    } else {
      logger.warn(getContikiFirmwareFile().getName() + ": no readonly section found");
    }
    if (addresses.size() == 0) {
      throw new MoteTypeCreationException("Library variables parsing failed");
    }
    if (dataSectionAddr <= 0 || dataSectionSize <= 0
        || bssSectionAddr <= 0 || bssSectionSize <= 0) {
      throw new MoteTypeCreationException("Library section addresses parsing failed");
    }

    try {
      /* Relative <-> absolute addresses offset */
      int referenceVar = addresses.get("referenceVar");
      myCoreComm.setReferenceAddress(referenceVar);
    } catch (Exception e) {
      throw (MoteTypeCreationException) new MoteTypeCreationException(
          "JNI call error: " + e.getMessage()).initCause(e);
    }

    /* We first need the value of Contiki's referenceVar, which tells us the
     * memory offset between Contiki's variable and the relative addresses that
     * were calculated directly from the library file.
     *
     * This offset will be used in Cooja in the memory abstraction to match
     * Contiki's and Cooja's address spaces */
    int offset;
    {
      SectionMoteMemory tmp = new SectionMoteMemory(addresses, 0);
      byte[] data = new byte[dataSectionSize];
      getCoreMemory(dataSectionAddr, dataSectionSize, data);
      tmp.setMemorySegment(dataSectionAddr, data);
      byte[] bss = new byte[bssSectionSize];
      getCoreMemory(bssSectionAddr, bssSectionSize, bss);
      tmp.setMemorySegment(bssSectionAddr, bss);

      offset = tmp.getIntValueOf("referenceVar");
      logger.info(getContikiFirmwareFile().getName() +
          ": offsetting Cooja mote address space: " + offset);
    }

    /* Create initial memory: data+bss+optional common */
    initialMemory = new SectionMoteMemory(addresses, offset);

    byte[] initialDataSection = new byte[dataSectionSize];
    getCoreMemory(dataSectionAddr, dataSectionSize, initialDataSection);
    initialMemory.setMemorySegmentNative(dataSectionAddr, initialDataSection);

    byte[] initialBssSection = new byte[bssSectionSize];
    getCoreMemory(bssSectionAddr, bssSectionSize, initialBssSection);
    initialMemory.setMemorySegmentNative(bssSectionAddr, initialBssSection);

    if (commonSectionAddr >= 0 && commonSectionSize > 0) {
      byte[] initialCommonSection = new byte[commonSectionSize];
      getCoreMemory(commonSectionAddr, commonSectionSize, initialCommonSection);
      initialMemory.setMemorySegmentNative(commonSectionAddr, initialCommonSection);
    }

    /* Read "read-only" memory */
    if (readonlySectionAddr >= 0 && readonlySectionSize > 0) {
      byte[] readonlySection = new byte[readonlySectionSize];
      getCoreMemory(readonlySectionAddr, readonlySectionSize, readonlySection);
      initialMemory.setReadonlyMemorySegment(readonlySectionAddr+offset, readonlySection);
    }
  }

  /**
   * Ticks the currently loaded mote. This should not be used directly, but
   * rather via {@link ContikiMote#execute(long)}.
   */
  public void tick() {
    myCoreComm.tick();
  }

  /**
   * Creates and returns a copy of this mote type's initial memory (just after
   * the init function has been run). When a new mote is created it should get
   * it's memory from here.
   *
   * @return Initial memory of a mote type
   */
  public SectionMoteMemory createInitialMemory() {
    return initialMemory.clone();
  }

  /**
   * Copy given memory to the Contiki system. This should not be used directly,
   * but instead via ContikiMote.setMemory().
   *
   * @param mem
   *          New memory
   */
  public void setCoreMemory(SectionMoteMemory mem) {
    for (int i = 0; i < mem.getNumberOfSections(); i++) {
      setCoreMemory(
          mem.getSectionNativeAddress(i) /* native address space */,
          mem.getSizeOfSection(i), mem.getDataOfSection(i));
    }
  }

  /**
   * Parses specified map file data for variable name to addresses mappings. The
   * mappings are added to the given properties object.
   *
   * @param mapFileData
   *          Contents of entire map file
   * @param varAddresses
   *          Properties that should contain the name to addresses mappings.
   */
  public static boolean parseMapFileData(String[] mapFileData, HashMap<String, Integer> varAddresses) {
    String[] varNames = getMapFileVarNames(mapFileData);
    if (varNames == null || varNames.length == 0) {
      return false;
    }

    for (String varName : varNames) {
      int varAddress = getMapFileVarAddress(mapFileData, varName, varAddresses);
      if (varAddress > 0) {
        varAddresses.put(varName, new Integer(varAddress));
      } else {
        logger.warn("Parsed Contiki variable '" + varName
            + "' but could not find address");
      }
    }

    return true;
  }

  /**
   * Parses parse command output for variable name to addresses mappings.
   * The mappings are written to the given properties object.
   *
   * @param output Command output
   * @param addresses Variable addresses mappings
   */
  public static boolean parseCommandData(String[] output, HashMap<String, Integer> addresses) {
    int nrNew = 0, nrOld = 0, nrMismatch = 0;

    Pattern pattern =
      Pattern.compile(GUI.getExternalToolsSetting("COMMAND_VAR_NAME_ADDRESS"));

    for (String line : output) {
      Matcher matcher = pattern.matcher(line);

      if (matcher.find()) {
        /* Line matched variable address */
        String symbol = matcher.group(2);
        int address = Integer.parseInt(matcher.group(1), 16);

        if (!addresses.containsKey(symbol)) {
          nrNew++;
          addresses.put(symbol, new Integer(address));
        } else {
          int oldAddress = addresses.get(symbol);
          if (oldAddress != address) {
            /*logger.warn("Warning, command response not matching previous entry of: "
                + varName);*/
            nrMismatch++;
          }
          nrOld++;
        }
      }
    }

    /*if (nrMismatch > 0) {
      logger.debug("Command response parsing summary: Added " + nrNew
          + " variables. Found " + nrOld
          + " old variables. Mismatching addresses: " + nrMismatch);
    } else {
      logger.debug("Command response parsing summary: Added " + nrNew
          + " variables. Found " + nrOld + " old variables");
    }*/

    return (nrNew + nrOld) > 0;
  }

  /**
   * Copy core memory to given memory. This should not be used directly, but
   * instead via ContikiMote.getMemory().
   *
   * @param mem
   *          Memory to set
   */
  public void getCoreMemory(SectionMoteMemory mem) {
    for (int i = 0; i < mem.getNumberOfSections(); i++) {
      int startAddr = mem.getSectionNativeAddress(i); /* native address space */
      int size = mem.getSizeOfSection(i);
      byte[] data = mem.getDataOfSection(i);
      getCoreMemory(startAddr, size, data);
    }
  }

  public String getIdentifier() {
    return identifier;
  }

  public void setIdentifier(String identifier) {
    this.identifier = identifier;
  }

  public File getContikiSourceFile() {
    return fileSource;
  }

  public void setContikiSourceFile(File file) {
    fileSource = file;
  }

  public File getContikiFirmwareFile() {
    return fileFirmware;
  }

  public void setContikiFirmwareFile(File file) {
    fileFirmware = file;
  }

  public String getCompileCommands() {
    return compileCommands;
  }

  public void setCompileCommands(String commands) {
    this.compileCommands = commands;
  }

  /**
   * @param symbols Core library has system symbols information
   */
  public void setHasSystemSymbols(boolean symbols) {
    hasSystemSymbols = symbols;
  }

  /**
   * @return Whether core library has system symbols information
   */
  public boolean hasSystemSymbols() {
    return hasSystemSymbols;
  }

  /**
   * @param netStack Contiki network stack
   */
  public void setNetworkStack(NetworkStack netStack) {
    this.netStack = netStack;
  }

  /**
   * @return Contiki network stack
   */
  public NetworkStack getNetworkStack() {
    return netStack;
  }

  /**
   * Get relative address of variable with given name.
   *
   * @param varName Name of variable
   * @return Relative memory address of variable or -1 if not found
   */
  private static int getMapFileVarAddress(String[] mapFileData, String varName, HashMap<String, Integer> varAddresses) {
    Integer varAddrInteger;
    if ((varAddrInteger = varAddresses.get(varName)) != null) {
      return varAddrInteger.intValue();
    }

    String regExp =
      GUI.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") +
      varName +
      GUI.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2");
    String retString = getFirstMatchGroup(mapFileData, regExp, 1);

    if (retString != null) {
      varAddrInteger = Integer.parseInt(retString.trim(), 16);
      varAddresses.put(varName, varAddrInteger);
      return varAddrInteger.intValue();
    } else {
      return -1;
    }
  }

  private void getCoreMemory(int relAddr, int length, byte[] data) {
    myCoreComm.getMemory(relAddr, length, data);
  }

  private void setCoreMemory(int relAddr, int length, byte[] mem) {
    myCoreComm.setMemory(relAddr, length, mem);
  }

  private static String getFirstMatchGroup(String[] lines, String regexp, int groupNr) {
    Pattern pattern = Pattern.compile(regexp);
    for (String line : lines) {
      Matcher matcher = pattern.matcher(line);
      if (matcher.find()) {
        return matcher.group(groupNr);
      }
    }
    return null;
  }

  /**
   * Returns all variable names in both data and BSS section by parsing the map
   * file. These values should not be trusted completely as the parsing may
   * fail.
   *
   * @return Variable names found in the data and bss section
   */
  public static String[] getMapFileVarNames(String[] mapFileData) {
    ArrayList<String> varNames = new ArrayList<String>();

    String[] dataVariables = getAllVariableNames(
        mapFileData,
        parseMapDataSectionAddr(mapFileData),
        parseMapDataSectionAddr(mapFileData) + parseMapDataSectionSize(mapFileData));
    for (String v: dataVariables) {
      varNames.add(v);
    }

    String[] bssVariables = getAllVariableNames(
        mapFileData,
        parseMapBssSectionAddr(mapFileData),
        parseMapBssSectionAddr(mapFileData) + parseMapBssSectionSize(mapFileData));
    for (String v: bssVariables) {
      varNames.add(v);
    }

    return varNames.toArray(new String[0]);
  }

  private static String[] getAllVariableNames(String[] lines,
      int startAddress, int endAddress) {
    ArrayList<String> varNames = new ArrayList<String>();

    Pattern pattern = Pattern.compile(GUI.getExternalToolsSetting("MAPFILE_VAR_NAME"));
    for (String line : lines) {
      Matcher matcher = pattern.matcher(line);
      if (matcher.find()) {
        if (Integer.decode(matcher.group(1)).intValue() >= startAddress
            && Integer.decode(matcher.group(1)).intValue() <= endAddress) {
          varNames.add(matcher.group(2));
        }
      }
    }
    return varNames.toArray(new String[0]);
  }

  protected int getVariableSize(Vector<String> lines, String varName) {
    Pattern pattern = Pattern.compile(
        GUI.getExternalToolsSetting("MAPFILE_VAR_SIZE_1") +
        varName +
        GUI.getExternalToolsSetting("MAPFILE_VAR_SIZE_2"));
    for (int i = 0; i < lines.size(); i++) {
      Matcher matcher = pattern.matcher(lines.get(i));
      if (matcher.find()) {
        return Integer.decode(matcher.group(1));
      }
    }
    return -1;
  }

  private static int parseFirstHexInt(String regexp, String[] data) {
    String retString =
      getFirstMatchGroup(data, regexp, 1);

    if (retString != null) {
      return Integer.parseInt(retString.trim(), 16);
    } else {
      return -1;
    }
  }

  public static int parseMapDataSectionAddr(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_DATA_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }
  public static int parseMapDataSectionSize(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_DATA_SIZE", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }
  public static int parseMapBssSectionAddr(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_BSS_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }
  public static int parseMapBssSectionSize(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_BSS_SIZE", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }
  public static int parseMapCommonSectionAddr(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_COMMON_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }
  public static int parseMapCommonSectionSize(String[] mapFileData) {
    String regexp = GUI.getExternalToolsSetting("MAPFILE_COMMON_SIZE", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, mapFileData);
  }

  public static int parseCommandDataSectionAddr(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_DATA_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, output);
  }
  public static int parseCommandDataSectionSize(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_DATA_END", "");
    if (regexp.equals("")) {
      return -1;
    }
    int start = parseCommandDataSectionAddr(output);
    if (start < 0) {
      return -1;
    }

    int end = parseFirstHexInt(regexp, output);
    if (end < 0) {
      return -1;
    }
    return end - start;
  }
  public static int parseCommandBssSectionAddr(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_BSS_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, output);
  }
  public static int parseCommandBssSectionSize(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_BSS_END", "");
    if (regexp.equals("")) {
      return -1;
    }
    int start = parseCommandBssSectionAddr(output);
    if (start < 0) {
      return -1;
    }

    int end = parseFirstHexInt(regexp, output);
    if (end < 0) {
      return -1;
    }
    return end - start;
  }
  public static int parseCommandCommonSectionAddr(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_COMMON_START", "");
    if (regexp.equals("")) {
      return -1;
    }
    return parseFirstHexInt(regexp, output);
  }
  public static int parseCommandCommonSectionSize(String[] output) {
    String regexp = GUI.getExternalToolsSetting("COMMAND_COMMON_END", "");
    if (regexp.equals("")) {
      return -1;
    }
    int start = parseCommandCommonSectionAddr(output);
    if (start < 0) {
      return -1;
    }

    int end = parseFirstHexInt(regexp, output);
    if (end < 0) {
      return -1;
    }
    return end - start;
  }

  private static int parseCommandReadonlySectionAddr(String[] output) {
    return parseFirstHexInt("^([0-9A-Fa-f]*)[ \t]t[ \t].text$", output);
  }
  private static int parseCommandReadonlySectionSize(String[] output) {
    int start = parseCommandReadonlySectionAddr(output);
    if (start < 0) {
      return -1;
    }

    /* Extract the last specified address, assuming that the interval covers all the memory */
    String last  = output[output.length-1];
    int lastAddress = Integer.parseInt(last.split("[ \t]")[0],16);
    return lastAddress - start;
  }

  private static int getRelVarAddr(String mapFileData[], String varName) {
    String regExp =
      GUI.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") +
      varName +
      GUI.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2");
    String retString = getFirstMatchGroup(mapFileData, regExp, 1);

    if (retString != null) {
      return Integer.parseInt(retString.trim(), 16);
    } else {
      return -1;
    }
  }

  public static String[] loadMapFile(File mapFile) {
    String contents = StringUtils.loadFromFile(mapFile);
    if (contents == null) {
      return null;
    }
    return contents.split("\n");
  }

  /**
   * Executes configured command on given file and returns the result.
   *
   * @param libraryFile Contiki library
   * @return Execution response, or null at failure
   */
  public static String[] loadCommandData(File libraryFile) {
    ArrayList<String> output = new ArrayList<String>();

    try {
      String command = GUI.getExternalToolsSetting("PARSE_COMMAND");
      if (command == null) {
        return null;
      }

      /* Prepare command */
      command = command.replace("$(LIBFILE)",
          libraryFile.getName().replace(File.separatorChar, '/'));

      /* Execute command, read response */
      String line;
      Process p = Runtime.getRuntime().exec(
          command.split(" "),
          null,
          libraryFile.getParentFile()
      );
      BufferedReader input = new BufferedReader(
          new InputStreamReader(p.getInputStream())
      );
      p.getErrorStream().close();
      while ((line = input.readLine()) != null) {
        output.add(line);
      }
      input.close();

      if (output == null || output.size() == 0) {
        return null;
      }
      return output.toArray(new String[0]);
    } catch (Exception err) {
      logger.fatal("Command error: " + err.getMessage(), err);
      return null;
    }
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String newDescription) {
    description = newDescription;
  }

  public ProjectConfig getConfig() {
    return myConfig;
  }

  /**
   * Sets mote type project configuration. This may differ from the general
   * simulator project configuration.
   *
   * @param moteTypeConfig
   *          Project configuration
   */
  public void setConfig(ProjectConfig moteTypeConfig) {
    myConfig = moteTypeConfig;
  }

  /**
   * Returns all sensors of this mote type
   *
   * @return All sensors
   */
  public String[] getSensors() {
    return sensors;
  }

  /**
   * Returns all core interfaces of this mote type
   *
   * @return All core interfaces
   */
  public String[] getCoreInterfaces() {
    return coreInterfaces;
  }

  /**
   * Set core interfaces
   *
   * @param coreInterfaces
   *          New core interfaces
   */
  public void setCoreInterfaces(String[] coreInterfaces) {
    this.coreInterfaces = coreInterfaces;
  }

  public Class<? extends MoteInterface>[] getMoteInterfaceClasses() {
    if (moteInterfacesClasses == null) {
      return null;
    }
    Class<? extends MoteInterface>[] arr = new Class[moteInterfacesClasses.size()];
    moteInterfacesClasses.toArray(arr);
    return arr;
  }

  public void setMoteInterfaceClasses(Class<? extends MoteInterface>[] moteInterfaces) {
    this.moteInterfacesClasses = new ArrayList<Class<? extends MoteInterface>>();
    for (Class<? extends MoteInterface> intf: moteInterfaces) {
      this.moteInterfacesClasses.add(intf);
    }
  }

  /**
   * Create a checksum of file. Used for checking if needed files are unchanged
   * when loading a saved simulation.
   *
   * @param file
   *          File containg data to checksum
   * @return Checksum
   */
  protected byte[] createChecksum(File file) {
    int bytesRead = 1;
    byte[] readBytes = new byte[128];
    MessageDigest messageDigest;

    try {
      InputStream fileInputStream = new FileInputStream(file);
      messageDigest = MessageDigest.getInstance("MD5");

      while (bytesRead > 0) {
        bytesRead = fileInputStream.read(readBytes);
        if (bytesRead > 0) {
          messageDigest.update(readBytes, 0, bytesRead);
        }
      }
      fileInputStream.close();
    } catch (NoSuchAlgorithmException e) {
      return null;
    } catch (IOException e) {
      return null;
    }
    return messageDigest.digest();
  }

  /**
   * Generates a unique Cooja mote type ID.
   *
   * @param existingTypes Already existing mote types, may be null
   * @param reservedIdentifiers Already reserved identifiers, may be null
   * @return Unique mote type ID.
   */
  public static String generateUniqueMoteTypeID(MoteType[] existingTypes, Collection reservedIdentifiers) {
    String testID = "";
    boolean okID = false;

    while (!okID) {
      testID = ID_PREFIX + (new Random().nextInt(1000));
      okID = true;

      // Check if identifier is reserved
      if (reservedIdentifiers != null && reservedIdentifiers.contains(testID)) {
        okID = false;
      }

      if (!okID) {
        continue;
      }

      // Check if identifier is used
      if (existingTypes != null) {
        for (MoteType existingMoteType : existingTypes) {
          if (existingMoteType.getIdentifier().equals(testID)) {
            okID = false;
            break;
          }
        }
      }

      if (!okID) {
        continue;
      }

      // Check if identifier library has been loaded
      /* XXX Currently only checks the build directory! */
      File libraryFile = new File(
          ContikiMoteType.tempOutputDirectory,
          testID + ContikiMoteType.librarySuffix);
      if (libraryFile.exists() || CoreComm.hasLibraryFileBeenLoaded(libraryFile)) {
        okID = false;
      }
    }

    return testID;
  }

  /**
   * Returns a panel with interesting data for this mote type.
   *
   * @return Mote type visualizer
   */
  public JComponent getTypeVisualizer() {
    StringBuilder sb = new StringBuilder();
    // Identifier
    sb.append("

Identifier	")
    .append(getIdentifier()).append("
");

    // Description
    sb.append("
Description	")
    .append(getDescription()).append("
");

    /* Contiki application */
    sb.append("
Contiki application	")
    .append(getContikiSourceFile().getAbsolutePath()).append("
");

    /* Contiki firmware */
    sb.append("
Contiki firmware	")
    .append(getContikiFirmwareFile().getAbsolutePath()).append("
");

    /* JNI class */
    sb.append("
JNI library	")
    .append(this.javaClassName).append("
");

    /* Contiki sensors */
    sb.append("
Contiki sensors	");
    for (String sensor: sensors) {
      sb.append(sensor).append("
");
    }
    sb.append("
");

    /* Mote interfaces */
    sb.append("
Mote interface	");
    for (Class<? extends MoteInterface> moteInterface: moteInterfacesClasses) {
      sb.append(moteInterface.getSimpleName()).append("
");
    }
    sb.append("
");

    /* Contiki core mote interfaces */
    sb.append("
Contiki's mote interface	");
    for (String coreInterface: getCoreInterfaces()) {
      sb.append(coreInterface).append("
");
    }
    sb.append("
");

    JLabel label = new JLabel(sb.append("
").toString());
    label.setVerticalTextPosition(JLabel.TOP);
    return label;
  }

  public Collection<Element> getConfigXML(Simulation simulation) {
    ArrayList<Element> config = new ArrayList<Element>();
    Element element;

    element = new Element("identifier");
    element.setText(getIdentifier());
    config.add(element);

    element = new Element("description");
    element.setText(getDescription());
    config.add(element);

    element = new Element("source");
    File file = simulation.getGUI().createPortablePath(getContikiSourceFile());
    element.setText(file.getPath().replaceAll("\\\\", "/"));
    config.add(element);

    element = new Element("commands");
    element.setText(compileCommands);
    config.add(element);

    for (Class<? extends MoteInterface> moteInterface : getMoteInterfaceClasses()) {
      element = new Element("moteinterface");
      element.setText(moteInterface.getName());
      config.add(element);
    }

    element = new Element("symbols");
    element.setText(new Boolean(hasSystemSymbols()).toString());
    config.add(element);

    if (getNetworkStack() != NetworkStack.DEFAULT) {
      element = new Element("netstack");
      element.setText(getNetworkStack().getConfig());
      config.add(element);
    }

    return config;
  }

  public boolean setConfigXML(Simulation simulation,
      Collection<Element> configXML, boolean visAvailable)
  throws MoteTypeCreationException {
    boolean warnedOldVersion = false;
    File oldVersionSource = null;

    moteInterfacesClasses = new ArrayList<Class<? extends MoteInterface>>();

    for (Element element : configXML) {
      String name = element.getName();

      if (name.equals("identifier")) {
        identifier = element.getText();
      } else if (name.equals("description")) {
        description = element.getText();
      } else if (name.equals("contikiapp") || name.equals("source")) {
        File file = new File(element.getText());
        if (!file.exists()) {
          file = simulation.getGUI().restorePortablePath(file);
        }

        setContikiSourceFile(file);

        /* XXX Do not load the generated firmware. Instead, load the unique library file directly */
        File contikiFirmware = new File(
            getContikiSourceFile().getParentFile(),
            "obj_cooja/" + getIdentifier() + librarySuffix);
        setContikiFirmwareFile(contikiFirmware);

      } else if (name.equals("commands")) {
        compileCommands = element.getText();
      } else if (name.equals("symbols")) {
        hasSystemSymbols = Boolean.parseBoolean(element.getText());
      } else if (name.equals("commstack")) {
        logger.warn("The Cooja communication stack config was removed: " + element.getText());
        logger.warn("Instead assuming default network stack.");
        netStack = NetworkStack.DEFAULT;
      } else if (name.equals("netstack")) {
        netStack = NetworkStack.parseConfig(element.getText());
      } else if (name.equals("moteinterface")) {
        if (element.getText().trim().equals("se.sics.cooja.contikimote.interfaces.ContikiLog")) {
          /* Backwards compatibility: ContikiLog was removed */
        } else {
          Class<? extends MoteInterface> moteInterfaceClass =
            simulation.getGUI().tryLoadClass(
                this, MoteInterface.class, element.getText().trim());

          if (moteInterfaceClass == null) {
            logger.warn("Can't find mote interface class: " + element.getText());
          } else {
            moteInterfacesClasses.add(moteInterfaceClass);
          }
        }
      } else if (
          name.equals("contikibasedir") ||
          name.equals("contikicoredir") ||
          name.equals("projectdir") ||
          name.equals("compilefile") ||
          name.equals("process") ||
          name.equals("sensor") ||
          name.equals("coreinterface")) {
        /* Backwards compatibility: old cooja mote type is being loaded */
        if (!warnedOldVersion) {
          warnedOldVersion = true;
          logger.warn("Old simulation config detected: Cooja mote types may not load correctly");
        }

        if (name.equals("compilefile")) {
          if (element.getText().endsWith(".c")) {
            File potentialFile = new File(element.getText());
            if (potentialFile.exists()) {
              oldVersionSource = potentialFile;
            }
          }
        }

      } else {
        logger.fatal("Unrecognized entry in loaded configuration: " + name);
      }
    }

    /* Create initial core interface dependencies */
    Class<? extends MoteInterface>[] arr =
      new Class[moteInterfacesClasses.size()];
    moteInterfacesClasses.toArray(arr);
    setCoreInterfaces(ContikiMoteType.getRequiredCoreInterfaces(arr));

    /* Backwards compatibility: old cooja mote type is being loaded */
    if (getContikiSourceFile() == null &&
        warnedOldVersion &&
        oldVersionSource != null)
    {
      /* Guess Contiki source */
      setContikiSourceFile(oldVersionSource);
      logger.info("Guessing Contiki source: " + oldVersionSource.getAbsolutePath());

      setContikiFirmwareFile(getExpectedFirmwareFile(oldVersionSource));
      logger.info("Guessing Contiki firmware: " + getContikiFirmwareFile().getAbsolutePath());

      /* Guess compile commands */
      String compileCommands =
        "make " + getExpectedFirmwareFile(oldVersionSource).getName() + " TARGET=cooja";
      logger.info("Guessing compile commands: " + compileCommands);
      setCompileCommands(compileCommands);
    }

    boolean createdOK = configureAndInit(GUI.getTopParentContainer(), simulation, visAvailable);
    return createdOK;
  }

  public static String[] getRequiredCoreInterfaces(
      Class<? extends MoteInterface>[] moteInterfaces) {
    /* Extract Contiki dependencies from currently selected mote interfaces */
    ArrayList<String> coreInterfacesList = new ArrayList<String>();
    for (Class<? extends MoteInterface> intf: moteInterfaces) {
      if (!ContikiMoteInterface.class.isAssignableFrom(intf)) {
        continue;
      }

      String[] deps;
      try {
        /* Call static method */
        Method m = intf.getDeclaredMethod("getCoreInterfaceDependencies", (Class[]) null);
        deps = (String[]) m.invoke(null, (Object[]) null);
      } catch (Exception e) {
        logger.warn("Could not extract Contiki dependencies of mote interface: " + intf.getName());
        e.printStackTrace();
        continue;
      }

      if (deps == null || deps.length == 0) {
        continue;
      }

      for (String dep: deps) {
        coreInterfacesList.add(dep);
      }
    }

    String[] coreInterfaces = new String[coreInterfacesList.size()];
    coreInterfacesList.toArray(coreInterfaces);
    return coreInterfaces;
  }

}


text:
namespace Microsoft.PowerShell.Commands.ShowCommandExtension
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Management.Automation;

    /// <summary>
    /// Implements a facade around CommandParameterSetInfo and its deserialized counterpart.
    /// </summary>
    public class ShowCommandParameterSetInfo
    {
        /// <summary>
        /// Creates an instance of the ShowCommandParameterSetInfo class based on a CommandParameterSetInfo object.
        /// </summary>
        /// <param name="other">
        /// The object to wrap.
        /// </param>
        public ShowCommandParameterSetInfo(CommandParameterSetInfo other)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            this.Name = other.Name;
            this.IsDefault = other.IsDefault;
            this.Parameters = other.Parameters.Select(x => new ShowCommandParameterInfo(x)).ToArray();
        }

        /// <summary>
        /// Creates an instance of the ShowCommandParameterSetInfo class based on a PSObject object.
        /// </summary>
        /// <param name="other">
        /// The object to wrap.
        /// </param>
        public ShowCommandParameterSetInfo(PSObject other)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            this.Name = other.Members["Name"].Value as string;
            this.IsDefault = (bool)(other.Members["IsDefault"].Value);
            var parameters = (other.Members["Parameters"].Value as PSObject).BaseObject as System.Collections.ArrayList;
            this.Parameters = ShowCommandCommandInfo.GetObjectEnumerable(parameters).Cast<PSObject>().Select(x => new ShowCommandParameterInfo(x)).ToArray();
        }

        /// <summary>
        /// Gets the name of the parameter set.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// Gets whether the parameter set is the default parameter set.
        /// </summary>
        public bool IsDefault { get; private set; }

        /// <summary>
        /// Gets the parameter information for the parameters in this parameter set.
        /// </summary>
        public ICollection<ShowCommandParameterInfo> Parameters { get; private set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kooboo.CMS.Search.Models;
using Kooboo.Web.Mvc.Grid;
using Kooboo.CMS.Web.Models;
using System.ComponentModel.DataAnnotations;
using Kooboo.Web.Mvc;
using Kooboo.CMS.Content.Models;
using System.ComponentModel;

namespace Kooboo.CMS.Web.Areas.Contents.Models
{
    [Grid(Checkable = true, IdProperty = "Name")]
    [GridAction(ActionName = "Edit", Class = "o-icon edit dialog-link", RouteValueProperties = "Name")]
    public class SearchSetting_Metadata
    {
        public string Name { get; set; }

        [Required]
        [GridColumn(ItemRenderType = typeof(CommonLinkPopColumnRender), Order = 0)]
        [UIHint("SingleFolderTree")]
        [DataSource(typeof(FolderTreeDataSource))]
        [RemoteEx("IsNameAvailable", "SearchSetting", RouteFields = "RepositoryName")]
        [Display(Name = "Folder name")]
        public string FolderName { get; set; }

        [Display(Name = "Include all fields")]
        [Description("Include all content fields in the search index or select special fields.")]
        public bool IncludeAllFields { get; set; }
        [UIHint("DropDownArray")]
        public List<string> Fields { get; set; }

        [GridColumn(Order = 1)]
        [Display(Name="Content Url format")]
        [Description("The URL format with parameters of content detail page. e.g.: /article/detail/{userkey}")]
        public string UrlFormat { get; set; }

        public Repository Repository { get; set; }
    }
}


text:
package au.net.zeus.rmi.tls;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedAction;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import net.jini.security.Security;
import org.apache.river.action.GetPropertyAction;

/**
 *
 *
 */
abstract class FilterX509TrustManager extends Utilities implements X509TrustManager {

    /* -- Fields -- */
    /** The trust manager to delegate to. */
    private static volatile X509TrustManager trustManager;

    /** Use for synchronizing initialization of the trustManager field. */
    private static final Object lock = new Object();

    /** The trust manager factory algorithm. */
    private static final String trustManagerFactoryAlgorithm =
	Security.doPrivileged(
	    new GetPropertyAction(
		"org.apache.river.jeri.ssl.trustManagerFactoryAlgorithm",
		TrustManagerFactory.getDefaultAlgorithm()
	    )
	);

    /** The set of permitted remote principals, or null if no restriction. */
    private Set principals;

    /* -- Constructors -- */

    /**
     * Creates an X509TrustManager that only trusts certificate chains whose
     * first certificate identifies one of a set of principals.
     *
     * @param principals the set of permitted remote principals, or null if no
     *	      restriction
     * @throws NoSuchAlgorithmException if the trust manager factory algorithm
     *	       is not found
     */
    FilterX509TrustManager() throws NoSuchAlgorithmException, NoSuchProviderException {
	synchronized (lock) {
	    if (trustManager == null) {
		trustManager = getTrustManager();
	    }
	}
//	setPermittedRemotePrincipals(principals);
    }

    /* -- Implement X509TrustManager -- */

    public void checkClientTrusted(X509Certificate[] chain, String authType)
	throws CertificateException
    {
	trustManager.checkClientTrusted(chain, authType);
	check(chain);
	if (SERVER_LOGGER.isLoggable(Level.FINE)) {
	    SERVER_LOGGER.log(Level.FINE,
			     "check client trusted succeeds " +
			     "for auth type {0}\nchain {1}",
			     new Object[] { authType, toString(chain) });
	}
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
	throws CertificateException
    {
	trustManager.checkServerTrusted(chain, authType);
	check(chain);
	if (CLIENT_LOGGER.isLoggable(Level.FINE)) {
	    CLIENT_LOGGER.log(Level.FINE,
			     "check server trusted succeeds " +
			     "for auth type {0}\nchain {1}",
			     new Object[] { authType, toString(chain) });
	}
    }

    public X509Certificate[] getAcceptedIssuers() {
	return trustManager.getAcceptedIssuers();
    }

    /* -- Other methods -- */

    /**
     * Specifies the set of permitted remote principals.
     *
     * @param principals the set of permitted remote principals, or null if no
     *	      restriction
     */
    synchronized void setPermittedRemotePrincipals(Set principals) {
	this.principals = (principals == null) ? null : new HashSet(principals);
    }

    /**
     * Make sure the subject of the leaf certificate is one of the permitted
     * principals.
     */
    private synchronized void check(X509Certificate[] chain) throws CertificateException {
	if (principals != null &&
	    !principals.contains(chain[0].getSubjectX500Principal()))
	{
	    throw new CertificateException("Remote principal is not trusted");
	}
    }

    /** Returns the X509TrustManager to delegate to. */
    private static X509TrustManager getTrustManager()
	throws NoSuchAlgorithmException, NoSuchProviderException
    {
	final TrustManagerFactory factory = JSSE_PROVIDER != null ?
		TrustManagerFactory.getInstance(trustManagerFactoryAlgorithm, JSSE_PROVIDER)
		: TrustManagerFactory.getInstance(trustManagerFactoryAlgorithm);
	Security.doPrivileged(
	    new PrivilegedAction() {
		public Object run() {
		    /*
		     * Initialize the trust managers for the trust manager
		     * factory.  Call in a doPrivileged because access to the
		     * CA certificates file should be allowed to all programs
		     * that use this provider.
		     */
		    try {
			/*
			 * Calling init with null reads the default truststore
			 */

                        KeyStore keyStore =
                        KeyStore.getInstance(
                            System.getProperty(
                                "javax.net.ssl.trustStoreType",
                                KeyStore.getDefaultType()
                            )
                        );
                        InputStream in;
                        try {
                            in = new FileInputStream(
                                    System.getProperty("javax.net.ssl.trustStore"));
                            String keyStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
                            char[] password = keyStorePassword != null ? keyStorePassword.toCharArray() : new char[0];
                            keyStore.load(in, password);
                            in.close();
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(FilterX509TrustManager.class.getName()).log(Level.CONFIG, "Unable to find trustStore", ex);
                        } catch (IOException ex) {
                            Logger.getLogger(FilterX509TrustManager.class.getName()).log(Level.CONFIG, "Unable to load trustStore", ex);
                        } catch (NoSuchAlgorithmException ex) {
                            Logger.getLogger(FilterX509TrustManager.class.getName()).log(Level.CONFIG, "Unable to load trustStore", ex);
                        } catch (CertificateException ex) {
                            Logger.getLogger(FilterX509TrustManager.class.getName()).log(Level.CONFIG, "Unable to load trustStore", ex);
                        }
			factory.init(keyStore);
		    } catch (KeyStoreException e) {
			INIT_LOGGER.log(
			    Level.WARNING,
			    "Problem initializing JSSE trust manager keystore",
			    e);
		    }
		    return null;
		}
	    });

	/*
	 * Although JSSE doesn't document this, there should be only one X.509
	 * trust manager for X.509 certificates read from KeyStores.
	 */
	return (X509TrustManager) factory.getTrustManagers()[0];
    }

}


text:
#ifndef AV1_ENCODER_RDOPT_H_
#define AV1_ENCODER_RDOPT_H_

#include "av1/common/blockd.h"
#include "av1/common/txb_common.h"

#include "av1/encoder/block.h"
#include "av1/encoder/context_tree.h"
#include "av1/encoder/encoder.h"
#include "av1/encoder/encodetxb.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MAX_REF_MV_SERCH 3

struct TileInfo;
struct macroblock;
struct RD_STATS;

#if CONFIG_RD_DEBUG
static INLINE void av1_update_txb_coeff_cost(RD_STATS *rd_stats, int plane,
                                             TX_SIZE tx_size, int blk_row,
                                             int blk_col, int txb_coeff_cost) {
  (void)blk_row;
  (void)blk_col;
  (void)tx_size;
  rd_stats->txb_coeff_cost[plane] += txb_coeff_cost;

  {
    const int txb_h = tx_size_high_unit[tx_size];
    const int txb_w = tx_size_wide_unit[tx_size];
    int idx, idy;
    for (idy = 0; idy < txb_h; ++idy)
      for (idx = 0; idx < txb_w; ++idx)
        rd_stats->txb_coeff_cost_map[plane][blk_row + idy][blk_col + idx] = 0;

    rd_stats->txb_coeff_cost_map[plane][blk_row][blk_col] = txb_coeff_cost;
  }
  assert(blk_row < TXB_COEFF_COST_MAP_SIZE);
  assert(blk_col < TXB_COEFF_COST_MAP_SIZE);
}
#endif

typedef enum OUTPUT_STATUS {
  OUTPUT_HAS_PREDICTED_PIXELS,
  OUTPUT_HAS_DECODED_PIXELS
} OUTPUT_STATUS;

// Returns the number of colors in 'src'.
int av1_count_colors(const uint8_t *src, int stride, int rows, int cols,
                     int *val_count);
// Same as av1_count_colors(), but for high-bitdepth mode.
int av1_count_colors_highbd(const uint8_t *src8, int stride, int rows, int cols,
                            int bit_depth, int *val_count);

#if CONFIG_DIST_8X8
int64_t av1_dist_8x8(const struct AV1_COMP *const cpi, const MACROBLOCK *x,
                     const uint8_t *src, int src_stride, const uint8_t *dst,
                     int dst_stride, const BLOCK_SIZE tx_bsize, int bsw,
                     int bsh, int visible_w, int visible_h, int qindex);
#endif

static INLINE int av1_cost_skip_txb(MACROBLOCK *x, TXB_CTX *txb_ctx, int plane,
                                    TX_SIZE tx_size) {
  const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
  const PLANE_TYPE plane_type = get_plane_type(plane);
  const LV_MAP_COEFF_COST *const coeff_costs =
      &x->coeff_costs[txs_ctx][plane_type];
  return coeff_costs->txb_skip_cost[txb_ctx->txb_skip_ctx][1];
}

static INLINE int av1_cost_coeffs(const AV1_COMMON *const cm, MACROBLOCK *x,
                                  BLOCK_SIZE plane_bsize, int plane,
                                  int blk_row, int blk_col, int block,
                                  TX_SIZE tx_size, const ENTROPY_CONTEXT *a,
                                  const ENTROPY_CONTEXT *l,
                                  int use_fast_coef_costing) {
#if TXCOEFF_COST_TIMER
  struct aom_usec_timer timer;
  aom_usec_timer_start(&timer);
#endif
  (void)use_fast_coef_costing;
  TXB_CTX txb_ctx;
  get_txb_ctx(plane_bsize, tx_size, plane, a, l, &txb_ctx);
  const int cost = av1_cost_coeffs_txb(cm, x, plane, blk_row, blk_col, block,
                                       tx_size, &txb_ctx);
#if TXCOEFF_COST_TIMER
  AV1_COMMON *tmp_cm = (AV1_COMMON *)&cpi->common;
  aom_usec_timer_mark(&timer);
  const int64_t elapsed_time = aom_usec_timer_elapsed(&timer);
  tmp_cm->txcoeff_cost_timer += elapsed_time;
  ++tmp_cm->txcoeff_cost_count;
#endif
  return cost;
}

void av1_rd_pick_intra_mode_sb(const struct AV1_COMP *cpi, struct macroblock *x,
                               int mi_row, int mi_col, struct RD_STATS *rd_cost,
                               BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx,
                               int64_t best_rd);

unsigned int av1_get_sby_perpixel_variance(const struct AV1_COMP *cpi,
                                           const struct buf_2d *ref,
                                           BLOCK_SIZE bs);
unsigned int av1_high_get_sby_perpixel_variance(const struct AV1_COMP *cpi,
                                                const struct buf_2d *ref,
                                                BLOCK_SIZE bs, int bd);

void av1_rd_pick_inter_mode_sb(const struct AV1_COMP *cpi,
                               struct TileDataEnc *tile_data,
                               struct macroblock *x, int mi_row, int mi_col,
                               struct RD_STATS *rd_cost, BLOCK_SIZE bsize,
                               PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far);

void av1_rd_pick_inter_mode_sb_seg_skip(
    const struct AV1_COMP *cpi, struct TileDataEnc *tile_data,
    struct macroblock *x, int mi_row, int mi_col, struct RD_STATS *rd_cost,
    BLOCK_SIZE bsize, PICK_MODE_CONTEXT *ctx, int64_t best_rd_so_far);

void av1_inverse_transform_block_facade(MACROBLOCKD *xd, int plane, int block,
                                        int blk_row, int blk_col, int eob,
                                        int reduced_tx_set);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AV1_ENCODER_RDOPT_H_


text:
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * @author Chase Fugett
 * @purpose creates a 10x10 battleship board with the player board
 * and the AI board shown, as well as buttons for submitting move and
 * starting a new game
 */
public class Battleship extends JFrame {

	private static final int FRAME_WIDTH = 800;
	private static final int FRAME_HEIGHT = 800;

	private JLabel message;
	private JButton submitMove;
	private JButton newGame;

	private BattleButton button1;
	private BattleButton button2;
	private BattleButton button3;

	private Image image1;
	private Image image2;
	private Image image3;

	private gameBoard gameBoard;

	/**
	 * Constructs the Battleship GUI
	 */
	public Battleship() {
		createControlPanel();
		this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
		this.setResizable(true);
	}

	/**
	 * Creates the control panel for the frame by calling methods to
	 * create the subpanels
	 */
	private void createControlPanel() {

	}

}


text:
using System.Collections;
using nHydrate.Generator.Common.GeneratorFramework;
using nHydrate.Generator.Common.Util;

namespace nHydrate.Generator.Common.EventArgs
{
	public class ProjectItemExistsEventArgs : System.EventArgs
	{
		#region Constructors

		public ProjectItemExistsEventArgs(string projectName, string itemName, ProjectItemType itemType)
		{
			this.ProjectName = projectName;
			this.ItemName = itemName;
			this.ItemType = itemType;
			this.Exists = false;
		}

		#endregion

		#region Property Implementations

		public string ItemName { get; }
		public string ProjectName { get; }
		public ProjectItemType ItemType { get; }
		public bool Exists { get; set; }

		#endregion

	}
}


text:
#ifndef _ASM_POWERPC_KDEBUG_H
#define _ASM_POWERPC_KDEBUG_H
#ifdef __KERNEL__

/* nearly identical to x86_64/i386 code */

#include <linux/notifier.h>

struct pt_regs;

struct die_args {
	struct pt_regs *regs;
	const char *str;
	long err;
	int trapnr;
	int signr;
};

/*
   Note - you should never unregister because that can race with NMIs.
   If you really want to do it first unregister - then synchronize_sched -
   then free.
 */
int register_die_notifier(struct notifier_block *nb);
extern struct notifier_block *powerpc_die_chain;

/* Grossly misnamed. */
enum die_val {
	DIE_OOPS = 1,
	DIE_IABR_MATCH,
	DIE_DABR_MATCH,
	DIE_BPT,
	DIE_SSTEP,
	DIE_PAGE_FAULT,
};

static inline int notify_die(enum die_val val,char *str,struct pt_regs *regs,long err,int trap, int sig)
{
	struct die_args args = { .regs=regs, .str=str, .err=err, .trapnr=trap,.signr=sig };
	return notifier_call_chain(&powerpc_die_chain, val, &args);
}

#endif /* __KERNEL__ */
#endif /* _ASM_POWERPC_KDEBUG_H */


text:
API is deprecated. Module is not functioning, until further notice.

## MMM-Events
* Rotation of upcoming events for your city.
* Never miss a show because you didn't know about it!
* Concerts and Tour Dates, Performing Arts, Art Galleries & Exhibits, Comedy Shows, Food and Drink, Sports, and more.

## Examples
Pictures with Frame or noFrame.

![](pix/rock1.JPG), ![](pix/rock2.JPG), ![](pix/rock3.JPG)

![](pix/rock4.JPG),![](pix/Events.JPG), ![](pix/EventsFrame.JPG)

## Installation

* `git clone https://github.com/mykle1/MMM-Events` into the `~/MagicMirror/modules` directory.
* Get FREE API key --> https://api.eventful.com/keys/new
* Annotated .css file included for your convenience.

## Config.js entry and options

      {
        disabled: f,
        module: 'MMM-Events',
        position: 'top_right',
        config: {
            city: "49.1829,0.3707", // "new york", or lat,long ex "40.123456,-74.123456",
            radius: "100", // search radius
            radiusDistance: "km", // mi or km
            eventType: "music,movies_film,art,sports", // Choose from Events List below
            when: "This Week",  // "All", "Future", "Past", "Today", "Last Week", "This Week", "Next week", and months
            mode: "noFrame",   // "Frame" or "noFrame" (around picture)
            apikey: "YOUR API KEY",
            rotateInterval: 5 * 60 * 1000,     // New Event Appears every 5 minutes
            useHeader: true,	           // Set to true if you want a header
            header: "Spectacle a proximité",
            animationSpeed: 3000,              // Event fades in and out
            picture: true,                     // true, false = no image
        }
      },

## For multiples of eventType
Seperate eventTypes (below) by commas (Ex. "music_electronic,music_jazz,music_vocal,music_rap_hiphop")

# Choose your config.js "eventType" from this list

## Concerts & Tour Dates

* music
* music_blues
* music_classical
* music_country
* music_dance
* music_easy_listening
* music_electronic
* music_folk
* music_jazz
* music_latin
* music_newage
* music_opera
* music_rb
* music_reggae
* music_vocal
* music_rap_hiphop
* music_metal
* music_religious
* music_rock
* music_pop
* music_world
* music_alternative
* music_childrens

## Performing Arts

* performing_arts
* performing_arts_cabaret
* performing_arts_opera
* performing_arts_dance
* performing_arts_musical
* performing_arts_ballet
* performing_arts_comedy
* performing_arts_theatre

## 	Sports

* sports
* sports_autoracing
* sports_dance
* sports_gymnastics
* sports_iceskatingskiing
* sports_softball
* sports_swimmingdiving
* sports_volleyball
* sports_baseball	Sports:
* sports_basketball
* sports_cricket
* sports_football
* sports_golf
* sports_hockey
* sports_rugby
* sports_soccer
* sports_tennis
* sports_wrestling

## Conferences & Tradeshows

* conference
* conference_career
* conference_convention
* conference_seminar
* conference_talkslectures

## Comedy

* comedy

## Education

* learning_education
* learning_education_classworkshop

## Kids & Family

* family_fun_kids

## Festivals

* festivals_parades
* festivals_parades_circus
* festivals_parades_festival
* festivals_parades_fairs
* festivals_parades_parade

## Film

* movies_film
* movies_film_filmfestival

## Food & Drink

* food
* food_beer
* food_wine
* food_farmersmarket
* food_tastings

## Fundraising & Charity

* fundraisers
* fundraisers_blooddrive
* fundraisers_volunteer

## Art Galleries & Exhibits

* art
* art_antiques
* art_painting
* art_photography
* art_artexhibits
* art_artsandcrafts
* art_fashion

## Health & Wellness

* support
* support_fitness
* support_seniorhealth
* support_support
* support_yoga

## Holiday

* holiday

## Literary & Books

* books
* books_poetry

## Museums & Attractions

* attractions

## Neighborhood

* community
* community_library
* community_holiday
* community_seasonal

## Business & Networking

* business

## 	Nightlife & Singles

* singles_social
* singles_social_trivianight
* singles_social_comedy
* singles_social_bars
* singles_social_dating
* singles_social_karaoke
* singles_social_openmic

## University & Alumni

* schools_alumni

## 	Organizations & Meetups

* clubs_associations

## Outdoors & Recreation

* outdoors_recreation
* outdoors_recreation_cycling
* outdoors_recreation_hiking
* outdoors_recreation_nature
* outdoors_recreation_running

## Pets

* animals
* animals_cats
* animals_dogs

## Politics & Activism

* politics_activism

##	Sales & Retail

* sales
* sales_auction
* sales_craftshow
* sales_fleamarket
* sales_yardsale
* sales_retail

## Science

* science

## 	Religion & Spirituality

* religion_spirituality

## Technology

* technology
* technology_computer


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Caripunas</logradouro><bairro>Tupi</bairro><cidade>Praia Grande</cidade><uf>SP</uf><cep>11703560</cep></feed>


text:
package groovy.security;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.Script;
import groovy.util.GroovyTestCase;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.ResultPrinter;
import org.codehaus.groovy.runtime.InvokerHelper;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.Permission;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.util.Enumeration;

public abstract class SecurityTestSupport extends GroovyTestCase {
    private static final String POLICY_FILE = "security/groovy.policy";
    private static int counter = 0;
    private static boolean securityDisabled;
    private static boolean securityAvailable;
    private static boolean securityChecked = false;

    static {
        if (System.getProperty("groovy.security.disabled") != null) {
            securityAvailable = false;
            securityDisabled = true;
        } else {
            securityDisabled = false;
            if (new File(POLICY_FILE).exists()) {
                securityAvailable = true;
                resetSecurityPolicy("=" + POLICY_FILE);
            } else {
                securityAvailable = false;
            }
        }
    }

    public static boolean isSecurityAvailable() {
        return securityAvailable;
    }

    public static boolean isSecurityDisabled() {
        return securityDisabled;
    }

    public static void resetSecurityPolicy(String policyFileURL) {
        System.setProperty("java.security.policy", policyFileURL);
        Policy.getPolicy().refresh();
    }

    protected class SecurityTestResultPrinter extends ResultPrinter {

        public SecurityTestResultPrinter(PrintStream stream) {
            super(stream);
        }

        public void print(TestResult result) {
            getWriter().println("Security testing on a groovy test failed:");
            printErrors(result);
            printFailures(result);
            printFooter(result);
        }
    }

    protected GroovyClassLoader loader =
            AccessController.doPrivileged(
                    new PrivilegedAction<GroovyClassLoader>() {
                        @Override
                        public GroovyClassLoader run() {
                            return new GroovyClassLoader(SecurityTestSupport.class.getClassLoader());
                        }
                    }
            );

    private SecurityManager securityManager;
    private ClassLoader currentClassLoader;

    public SecurityTestSupport() {
    }

    /*
      * Check SecuritySupport to see if security is properly configured.  If not, fail the first
      * test that runs.  All remaining tests will run, but not do any security checking.
      */
    private boolean checkSecurity() {
        if (!securityChecked) {
            securityChecked = true;
            if (!isSecurityAvailable()) {
                fail("Security is not available - skipping security tests.  Ensure that "
                        + POLICY_FILE + " is available from the current execution directory.");
            }
        }
        return isSecurityAvailable();
    }

    //Prepare for each security test.  First, check to see if groovy.lib can be determined via
    //a call to checkSecurity().  If not, fail() the first test.  Establish a security manager
    //and make the GroovyClassLoader the initiating class loader (ala GroovyShell) to compile AND
    //invoke the test scripts.  This handles cases where multiple .groovy scripts are involved in a
    //test case: a.groovy depends on b.groovy; a.groovy is parsed (and in the process the gcl
    //loads b.groovy via findClass).  Note that b.groovy is only available in the groovy class loader.
    //See
    protected void setUp() {
        if (checkSecurity()) {
            securityManager = System.getSecurityManager();
            if (securityManager == null) {
                System.setSecurityManager(new SecurityManager());
            }
        }
        currentClassLoader = Thread.currentThread().getContextClassLoader();
        AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                Thread.currentThread().setContextClassLoader(loader);
                return null;
            }
        });
    }

    protected void tearDown() {
        AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                System.setSecurityManager(securityManager);
                Thread.currentThread().setContextClassLoader(currentClassLoader);
                return null;
            }
        });
    }

    protected synchronized String generateClassName() {
        return "testSecurity" + (++counter);
    }

    /*
      * Execute the groovy script contained in file.  If missingPermission
      * is non-null, then this invocation expects an AccessControlException with missingPermission
      * as the reason.  If missingPermission is null, the script is expected to execute successfully.
      */
    protected Class parseClass(File file) {
        GroovyCodeSource gcs = null;
        try {
            gcs = new GroovyCodeSource(file);
        } catch (IOException fnfe) {
            fail(fnfe.toString());
        }
        return parseClass(gcs);
    }

    /*
     * Parse the Groovy code contained in the GroovyCodeSource as a privileged operation (i.e. do not
     * require the code source to have specific compile time permissions) and return the resulting class.
     */
    protected Class parseClass(final GroovyCodeSource gcs) {
        Class clazz = null;
        try {
            clazz = loader.parseClass(gcs);
        } catch (Exception e) {
            fail(e.toString());
        }
        return clazz;
    }

    /*
      * Parse the script contained in the GroovyCodeSource as a privileged operation (i.e. do not
      * require the code source to have specific compile time permissions).  If the class produced is a
      * TestCase, run the test in a suite and evaluate against the missingPermission.
      * Otherwise, run the class as a groovy script and evaluate against the missingPermission.
      */
    private void parseAndExecute(final GroovyCodeSource gcs, Permission missingPermission) {
        Class clazz = null;
        try {
            clazz = loader.parseClass(gcs);
        } catch (Exception e) {
            fail(e.toString());
        }
        if (TestCase.class.isAssignableFrom(clazz)) {
            executeTest(clazz, missingPermission);
        } else {
            executeScript(clazz, missingPermission);
        }
    }

    protected void executeTest(Class test, Permission missingPermission) {
        TestSuite suite = new TestSuite();
        suite.addTestSuite(test);
        TestResult result = new TestResult();
        suite.run(result);
        if (result.wasSuccessful()) {
            if (missingPermission == null) {
                return;
            } else {
                fail("Security test expected an AccessControlException on " + missingPermission + ", but did not receive one");
            }
        } else {
            if (missingPermission == null) {
                new SecurityTestResultPrinter(System.out).print(result);
                fail("Security test was expected to run successfully, but failed (results on System.out)");
            } else {
                //There may be more than 1 failure:  iterate to ensure that they all match the missingPermission.
                boolean otherFailure = false;
                for (Enumeration e = result.errors(); e.hasMoreElements();) {
                    TestFailure failure = (TestFailure) e.nextElement();
                    if (failure.thrownException() instanceof AccessControlException) {
                        AccessControlException ace = (AccessControlException) failure.thrownException();
                        if (missingPermission.implies(ace.getPermission())) {
                            continue;
                        }
                    }
                    otherFailure = true;
                    break;
                }
                if (otherFailure) {
                    new SecurityTestResultPrinter(System.out).print(result);
                    fail("Security test expected an AccessControlException on " + missingPermission + ", but failed for other reasons (results on System.out)");
                }
            }
        }
    }

    protected void executeScript(Class scriptClass, Permission missingPermission) {
        try {
            Script script = InvokerHelper.createScript(scriptClass, new Binding());
            script.run();
            //InvokerHelper.runScript(scriptClass, null);
        } catch (AccessControlException ace) {
            if (missingPermission != null && missingPermission.implies(ace.getPermission())) {
                return;
            } else {
                fail(ace.toString());
            }
        }
        if (missingPermission != null) {
            fail("Should catch an AccessControlException");
        }
    }

    /*
      * Execute the groovy script contained in file.  If missingPermission
      * is non-null, then this invocation expects an AccessControlException with missingPermission
      * as the reason.  If missingPermission is null, the script is expected to execute successfully.
      */
    protected void assertExecute(final File file, final Permission missingPermission) {
        if (!isSecurityAvailable()) {
            return;
        }
        // Use our privileged access in order to prevent checks lower in the call stack.  Otherwise we would have
        // to grant access to IDE unit test runners and unit test libs.  We only care about testing the call stack
        // higher upstream from this point of execution.
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                GroovyCodeSource gcs = null;
                try {
                    gcs = new GroovyCodeSource(file);
                } catch (IOException fnfe) {
                    fail(fnfe.toString());
                }
                parseAndExecute(gcs, missingPermission);
                return null;
            }
        });
    }

    /*
      * Execute the script represented by scriptStr using the supplied codebase.  If missingPermission
      * is non-null, then this invocation expects an AccessControlException with missingPermission
      * as the reason.  If missingPermission is null, the script is expected to execute successfully.
      */
    protected void assertExecute(final String scriptStr, String codeBase, final Permission missingPermission) {
        if (!isSecurityAvailable()) {
            return;
        }
        final String effectiveCodeBase = (codeBase != null) ? codeBase : "/groovy/security/test";
        // Use our privileged access in order to prevent checks lower in the call stack.  Otherwise we would have
        // to grant access to IDE unit test runners and unit test libs.  We only care about testing the call stack
        // higher upstream from this point of execution.
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                parseAndExecute(new GroovyCodeSource(scriptStr, generateClassName(), effectiveCodeBase), missingPermission);
                return null;
            }
        });
    }
}


text:
package org.elasticsearch.xpack.transform.notifications;

import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexTemplateMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.xpack.core.common.notifications.Level;
import org.elasticsearch.xpack.core.transform.transforms.persistence.TransformInternalIndexConstants;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/*
 * Test mock auditor to verify audit expectations.
 *
 * Shamelessly cop...inspired by {@link org.elasticsearch.test.MockLogAppender}
 *
 * TODO: ideally this would be a generalized  MockAuditor, but the current inheritance doesn't let us
 */
public class MockTransformAuditor extends TransformAuditor {

    private static final String MOCK_NODE_NAME = "mock_node_name";

    @SuppressWarnings("unchecked")
    public static MockTransformAuditor createMockAuditor() {
        ImmutableOpenMap.Builder<String, IndexTemplateMetadata> templates = ImmutableOpenMap.builder(1);
        templates.put(TransformInternalIndexConstants.AUDIT_INDEX, mock(IndexTemplateMetadata.class));
        Metadata metadata = mock(Metadata.class);
        when(metadata.getTemplates()).thenReturn(templates.build());
        ClusterState state = mock(ClusterState.class);
        when(state.getMetadata()).thenReturn(metadata);
        ClusterService clusterService = mock(ClusterService.class);
        when(clusterService.state()).thenReturn(state);

        return new MockTransformAuditor(clusterService);
    }

    private final List<AuditExpectation> expectations;

    public MockTransformAuditor(ClusterService clusterService) {
        super(mock(Client.class), MOCK_NODE_NAME, clusterService);
        expectations = new CopyOnWriteArrayList<>();
    }

    public void addExpectation(AuditExpectation expectation) {
        expectations.add(expectation);
    }

    // we can dynamically change the auditor, like attaching and removing the log appender
    public void reset() {
        expectations.clear();
    }

    @Override
    public void info(String resourceId, String message) {
        audit(Level.INFO, resourceId, message);
    }

    @Override
    public void warning(String resourceId, String message) {
        audit(Level.WARNING, resourceId, message);
    }

    @Override
    public void error(String resourceId, String message) {
        audit(Level.ERROR, resourceId, message);
    }

    public void assertAllExpectationsMatched() {
        for (AuditExpectation expectation : expectations) {
            expectation.assertMatched();
        }
    }

    public interface AuditExpectation {
        void match(Level level, String resourceId, String message);

        void assertMatched();
    }

    public abstract static class AbstractAuditExpectation implements AuditExpectation {
        protected final String expectedName;
        protected final Level expectedLevel;
        protected final String expectedResourceId;
        protected final String expectedMessage;
        volatile boolean saw;

        public AbstractAuditExpectation(String expectedName, Level expectedLevel, String expectedResourceId, String expectedMessage) {
            this.expectedName = expectedName;
            this.expectedLevel = expectedLevel;
            this.expectedResourceId = expectedResourceId;
            this.expectedMessage = expectedMessage;
            this.saw = false;
        }

        @Override
        public void match(final Level level, final String resourceId, final String message) {
            if (level.equals(expectedLevel) && resourceId.equals(expectedResourceId) && innerMatch(level, resourceId, message)) {
                if (Regex.isSimpleMatchPattern(expectedMessage)) {
                    if (Regex.simpleMatch(expectedMessage, message)) {
                        saw = true;
                    }
                } else {
                    if (message.contains(expectedMessage)) {
                        saw = true;
                    }
                }
            }
        }

        public boolean innerMatch(final Level level, final String resourceId, final String message) {
            return true;
        }
    }

    public static class SeenAuditExpectation extends AbstractAuditExpectation {

        public SeenAuditExpectation(String expectedName, Level expectedLevel, String expectedResourceId, String expectedMessage) {
            super(expectedName, expectedLevel, expectedResourceId, expectedMessage);
        }

        @Override
        public void assertMatched() {
            assertThat("expected to see " + expectedName + " but did not", saw, equalTo(true));
        }
    }

    public static class UnseenAuditExpectation extends AbstractAuditExpectation {

        public UnseenAuditExpectation(String expectedName, Level expectedLevel, String expectedResourceId, String expectedMessage) {
            super(expectedName, expectedLevel, expectedResourceId, expectedMessage);
        }

        @Override
        public void assertMatched() {
            assertThat("expected not to see " + expectedName + " but did", saw, equalTo(false));
        }
    }

    private void audit(Level level, String resourceId, String message) {
        for (AuditExpectation expectation : expectations) {
            expectation.match(level, resourceId, message);
        }
    }

}