{
    try {
      if (Velocity.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH) != null) {
        logger.debug(
            String.format(
                "Resource Loader Path: %s",
                Velocity.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH).toString()));
        shibbolethTemplate = Velocity.getTemplate("shibboleth/interface.vm");
      }
      JsonSimpleConfig config = new JsonSimpleConfig();

      SHIB_ATTRIBUTE_DELIMITER = config.getString(";", SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_DELIMITER);

      SHIB_SESSION_ID =
          config.getString("Shib-Session-ID", SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_SESSION_ATTR);
      SHIB_ATTRIBUTES.add(SHIB_SESSION_ID);
      SHIB_IDP =
          config.getString("Shib-Identity-Provide", SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_IDP_ATTRIBUTE);
      SHIB_ATTRIBUTES.add(SHIB_IDP);
      SHIB_COMMON_NAME = config.getString("cn", SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_CN_ATTRIBUTE);
      SHIB_ATTRIBUTES.add(SHIB_COMMON_NAME);
      SHIB_USER_NAME =
          config.getString("eppn", SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_USERNAME_ATTRIBUTE);
      SHIB_ATTRIBUTES.add(SHIB_USER_NAME);

      List attrs = config.getArray(SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_ATTRIBUTES);
      SHIB_ATTRIBUTES.addAll(attrs);

      SHIB_USE_HEADERS =
          config.getBoolean(SHIB_USE_HEADERS, SHIBBOLETH_PLUGIN_ID, SHIBBOLETH_USE_HEADERS);

      logger.debug(String.format("Session ID Attribute: %s", SHIB_SESSION_ID));
      logger.debug(String.format("Shib Identity Provider Attribute: %s", SHIB_IDP));
      logger.debug(String.format("Shib Common Name Attribute: %s", SHIB_COMMON_NAME));
      logger.debug(String.format("Shib Username Attribute: %s", SHIB_USER_NAME));
      logger.debug(String.format("Shib Attributes: %s", attrs));
      logger.debug(String.format("Shib Attribute split: %s", SHIB_ATTRIBUTE_DELIMITER));

      ServiceLoader<ShibbolethRoleManager> providers =
          ServiceLoader.load(ShibbolethRoleManager.class);
      List plugins = config.getArray(SHIBBOLETH_PLUGIN_ID, "rolePlugins");
      for (Object plugin : plugins) {
        for (ShibbolethRoleManager provider : providers) {
          if (provider.getId().equals(plugin.toString())) {
            logger.debug(String.format("Added Role Manager: %s", provider.getId()));
            roleManagers.add(provider);
          }
        }
      }

      serverUrlBase = config.getString(null, "urlBase");
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }
  /** Reset the transformer in preparation for a new object */
  private void reset() throws TransformerException {
    if (firstRun) {
      firstRun = false;
      // Output directory
      String outputPath = config.getString(null, "outputPath");
      if (outputPath == null) {
        throw new TransformerException("Output path not specified!");
      }
      outputDir = new File(outputPath);
      outputDir.mkdirs();

      // Rendition exclusions
      excludeList =
          Arrays.asList(StringUtils.split(config.getString(null, "excludeRenditionExt"), ','));

      // Conversion Service URL
      convertUrl = config.getString(null, "url");
      if (convertUrl == null) {
        throw new TransformerException("No ICE URL provided!");
      }
    }

    // Priority
    Boolean testResponse = itemConfig.getBoolean(null, "priority");
    if (testResponse != null) {
      // We found it in item config
      priority = testResponse;
    } else {
      // Try system config
      priority = config.getBoolean(true, "priority");
    }

    // Clear the old SAX reader
    reader = new SafeSAXReader();

    // Remove the last object
    thumbnails = null;
    previews = null;
  }
  /** Basic constructor, should be run automatically by Tapestry. */
  public PortalSecurityManagerImpl() throws IOException {
    // Get system configuration
    config = new JsonSimpleConfig();

    // For all SSO providers configured
    sso = new LinkedHashMap<String, SSOInterface>();
    for (String ssoId : config.getStringList("sso", "plugins")) {
      // Instantiate from the ServiceLoader
      SSOInterface valid = getSSOProvider(ssoId);
      if (valid == null) {
        log.error("Invalid SSO Implementation requested: '{}'", ssoId);
      } else {
        // Store valid implementations
        sso.put(ssoId, valid);
        log.info("SSO Provider instantiated: '{}'", ssoId);
      }
    }

    defaultPortal = config.getString(PortalManager.DEFAULT_PORTAL_NAME, "portal", "defaultView");
    serverUrlBase = config.getString(null, "urlBase");
    ssoLoginUrl = serverUrlBase + defaultPortal + SSO_LOGIN_PAGE;

    // Get exclusions Strings from config
    excStarts = config.getStringList("sso", "urlExclusions", "startsWith");
    excEnds = config.getStringList("sso", "urlExclusions", "endsWith");
    excEquals = config.getStringList("sso", "urlExclusions", "equals");

    // Trust tokens
    Map<String, JsonSimple> tokenMap = config.getJsonSimpleMap("sso", "trustTokens");
    tokens = new HashMap<String, String>();
    tokenExpiry = new HashMap<String, Long>();
    for (String key : tokenMap.keySet()) {
      JsonSimple tok = tokenMap.get(key);
      String publicKey = tok.getString(null, "publicKey");
      String privateKey = tok.getString(null, "privateKey");
      String expiry = tok.getString(TRUST_TOKEN_EXPIRY, "expiry");
      if (publicKey != null && privateKey != null) {
        // Valid key
        tokens.put(publicKey, privateKey);
        tokenExpiry.put(publicKey, Long.valueOf(expiry));
      } else {
        log.error("Invalid token data: '{}'", key);
      }
    }
  }
  /**
   * Main render method to send the file to ICE service
   *
   * @param sourceFile : File to be rendered
   * @return file returned by ICE service
   * @throws TransformerException
   */
  private File render(File sourceFile) throws TransformerException {
    log.info("Converting {}...", sourceFile);
    String filename = sourceFile.getName();
    String basename = FilenameUtils.getBaseName(filename);
    String ext = FilenameUtils.getExtension(filename);
    int status = HttpStatus.SC_OK;

    // Grab our config
    JsonObject object = itemConfig.getObject("resize");
    Map<String, JsonSimple> resizeConfig = JsonSimple.toJavaMap(object);

    if (resizeConfig == null || resizeConfig.isEmpty()) {
      // Try system config instead
      object = config.getObject("resize");
      resizeConfig = JsonSimple.toJavaMap(object);
      if (resizeConfig == null || resizeConfig.isEmpty()) {
        throw new TransformerException("No resizing configuration found.");
      }
    }

    String resizeJson = "";
    for (String key : resizeConfig.keySet()) {
      JsonSimple j = resizeConfig.get(key);
      resizeJson += "\"" + key + "\":" + j.toString() + ",";
    }

    PostMethod post = new PostMethod(convertUrl);
    try {
      Part[] parts = {
        new StringPart("zip", "on"),
        new StringPart("dc", "on"),
        new StringPart("toc", "on"),
        new StringPart("pdflink", "on"),
        new StringPart("addThumbnail", "on"),
        new StringPart("pathext", ext),
        new StringPart("template", getTemplate()),
        new StringPart(
            "multipleImageOptions", "{" + StringUtils.substringBeforeLast(resizeJson, ",") + "}"),
        new StringPart("mode", "download"),
        new FilePart("file", sourceFile)
      };
      post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
      BasicHttpClient client = new BasicHttpClient(convertUrl);
      log.debug("Using conversion URL: {}", convertUrl);
      status = client.executeMethod(post);
      log.debug("HTTP status: {} {}", status, HttpStatus.getStatusText(status));
    } catch (IOException ioe) {
      throw new TransformerException("Failed to send ICE conversion request", ioe);
    }
    try {
      if (status != HttpStatus.SC_OK) {
        String xmlError = post.getResponseBodyAsString();
        log.debug("Error: {}", xmlError);
        throw new TransformerException(xmlError);
      }
      String type = post.getResponseHeader("Content-Type").getValue();
      if ("application/zip".equals(type)) {
        filename = basename + ".zip";
      } else if (type.startsWith("image/")) {
        filename = basename + "_thumbnail.jpg";
      } else if ("video/x-flv".equals(type)) {
        filename = basename + ".flv";
      } else if ("audio/mpeg".equals(type)) {
        filename = basename + ".mp3";
      }
      File outputFile = new File(outputDir, filename);
      if (outputFile.exists()) {
        outputFile.delete();
      }
      InputStream in = post.getResponseBodyAsStream();
      FileOutputStream out = new FileOutputStream(outputFile);
      IOUtils.copy(in, out);
      in.close();
      out.close();
      log.debug("ICE output file: {}", outputFile);
      return outputFile;
    } catch (IOException ioe) {
      throw new TransformerException("Failed to process ICE output", ioe);
    }
  }