public void initialise(String scriptFullName, ServiceOperationInterface parentService) {

    String currentDirectory;

    File file = new File(scriptFullName);
    currentDirectory = file.getParent();

    if (startDirectory != null) {
      /* Relative directory... */
      if (startDirectory.startsWith(".")) {
        startDirectory = currentDirectory + File.separator + startDirectory;
        file = new File(startDirectory);
        try {
          startDirectory = file.getCanonicalPath();
        } catch (Exception ex) {
          log.warn("Could not convert the path [" + file.getAbsolutePath() + "]: " + ex.toString());
        }
      }
      /* else absolute directory specified... therefore just use the specified directory... */
    } else {
      /* No start directory specified, so use the scripts' directory... */
      startDirectory = currentDirectory;
    }

    log.info("startDirectory => [" + startDirectory + "]");

    this.parentService = parentService;

    return;
  }
 public void setProperty(String propertyKey, String propertyValue) {
   if (propertyKey.equals(GetPropertiesFile.START_DIRECTORY)) {
     startDirectory = propertyValue;
   } else if (propertyKey.equals(GetPropertiesFile.VALID_EXTENSIONS)) {
     validExtensions = propertyValue.split(",");
   } else {
     log.warn("The property [" + propertyKey + "] is not supported by the GetFileContents class.");
   }
 }
  public void invokeOperation(String responseFormat, ServiceScriptHelper helper) throws Exception {

    /* We expect that the properties file name is a parameter in the URL.. */

    String filename = parameters.getProperty(FILE_NAME_PARAM, "");

    if (filename.equals("")) {
      helper.errorResponse(
          "The [" + FILE_NAME_PARAM + "] parameter has not been specified.",
          responseFormat,
          parentService);
      return;
    }

    /* See if the client has specified a relative name... */

    File file;

    file = new File(startDirectory + File.separator + filename);

    log.info("***-> startDirectory = [" + file.getAbsolutePath() + "]");

    if (file.exists() == false) {
      helper.errorResponse(
          "The file [" + filename + "] could not be found.", responseFormat, parentService);
      return;
    }

    /* Check that the filename has a valid extension... */

    if (validExtensions.length > 0) {

      boolean valid = false;

      for (int idx = 0; idx < validExtensions.length; idx++) {
        if (filename.endsWith(validExtensions[idx].trim())) {
          valid = true;
          break;
        }
      }

      if (valid == false) {
        log.error("User tried to access a file [" + filename + "] with an invalid file extension.");
        helper.errorResponse(
            "The extension of the file you are trying to access is invalid.",
            responseFormat,
            parentService);
        return;
      }
    }

    /* Try to read the contents of the file into a string buffer... */

    StringBuffer content = new StringBuffer();

    try {
      FileInputStream fis = new FileInputStream(file);
      byte[] buf = new byte[1024];
      int len = 0;

      while ((len = fis.read(buf)) != -1) {
        content.append(new String(buf, 0, len));
      }

    } catch (Exception ex) {
      helper.errorResponse(
          "There was an exception reading the contents of the file ["
              + filename
              + "]: "
              + ex.toString(),
          responseFormat,
          parentService);
      return;
    }

    /** If the operation is to return RAW data then just write the file contents... */
    if (responseFormat.equals("RAW")) {
      helper.writeResponse(content.toString(), responseFormat, parentService);
      return;
    }

    /* Convert the contents into a base64 encoded string... */

    BASE64Encoder encoder = new BASE64Encoder();
    String encodedContent = encoder.encode(content.toString().getBytes());

    /* Build the response string... */

    StringBuffer responseString = new StringBuffer();

    responseString.append("<fileContents>");
    responseString.append(
        "<"
            + SetFileContents.FILENAME_ELEMENT
            + ">"
            + filename
            + "</"
            + SetFileContents.FILENAME_ELEMENT
            + ">");
    responseString.append(
        "<"
            + SetFileContents.ENCODEDCONTENT_ELEMENT
            + ">"
            + encodedContent
            + "</"
            + SetFileContents.ENCODEDCONTENT_ELEMENT
            + ">");
    responseString.append("</fileContents>");

    /* Send the list down to the client... */

    helper.writeResponse(responseString.toString(), responseFormat, parentService);

    return;
  }
/**
 * This class returns the contents of a file held on the server. The class will return the contents
 * in a base64 encoded string.
 */
public class GetFileContents implements CustomOperationInterface {

  /**
   * The name of the parameter that the user must specifiy the properties file content to return. *
   */
  public static String FILE_NAME_PARAM = "filename";

  private static Logger log = Logger.getLogger(GetPropertiesFile.class.getName());

  private Properties parameters;
  private String startDirectory;
  private ServiceOperationInterface parentService;
  private String validExtensions[];

  public GetFileContents() {
    parameters = new Properties();
  }

  public void clearParameters() {
    parameters.clear();
    return;
  }

  public void initialise(String scriptFullName, ServiceOperationInterface parentService) {

    String currentDirectory;

    File file = new File(scriptFullName);
    currentDirectory = file.getParent();

    if (startDirectory != null) {
      /* Relative directory... */
      if (startDirectory.startsWith(".")) {
        startDirectory = currentDirectory + File.separator + startDirectory;
        file = new File(startDirectory);
        try {
          startDirectory = file.getCanonicalPath();
        } catch (Exception ex) {
          log.warn("Could not convert the path [" + file.getAbsolutePath() + "]: " + ex.toString());
        }
      }
      /* else absolute directory specified... therefore just use the specified directory... */
    } else {
      /* No start directory specified, so use the scripts' directory... */
      startDirectory = currentDirectory;
    }

    log.info("startDirectory => [" + startDirectory + "]");

    this.parentService = parentService;

    return;
  }

  public void invokeOperation(String responseFormat, ServiceScriptHelper helper) throws Exception {

    /* We expect that the properties file name is a parameter in the URL.. */

    String filename = parameters.getProperty(FILE_NAME_PARAM, "");

    if (filename.equals("")) {
      helper.errorResponse(
          "The [" + FILE_NAME_PARAM + "] parameter has not been specified.",
          responseFormat,
          parentService);
      return;
    }

    /* See if the client has specified a relative name... */

    File file;

    file = new File(startDirectory + File.separator + filename);

    log.info("***-> startDirectory = [" + file.getAbsolutePath() + "]");

    if (file.exists() == false) {
      helper.errorResponse(
          "The file [" + filename + "] could not be found.", responseFormat, parentService);
      return;
    }

    /* Check that the filename has a valid extension... */

    if (validExtensions.length > 0) {

      boolean valid = false;

      for (int idx = 0; idx < validExtensions.length; idx++) {
        if (filename.endsWith(validExtensions[idx].trim())) {
          valid = true;
          break;
        }
      }

      if (valid == false) {
        log.error("User tried to access a file [" + filename + "] with an invalid file extension.");
        helper.errorResponse(
            "The extension of the file you are trying to access is invalid.",
            responseFormat,
            parentService);
        return;
      }
    }

    /* Try to read the contents of the file into a string buffer... */

    StringBuffer content = new StringBuffer();

    try {
      FileInputStream fis = new FileInputStream(file);
      byte[] buf = new byte[1024];
      int len = 0;

      while ((len = fis.read(buf)) != -1) {
        content.append(new String(buf, 0, len));
      }

    } catch (Exception ex) {
      helper.errorResponse(
          "There was an exception reading the contents of the file ["
              + filename
              + "]: "
              + ex.toString(),
          responseFormat,
          parentService);
      return;
    }

    /** If the operation is to return RAW data then just write the file contents... */
    if (responseFormat.equals("RAW")) {
      helper.writeResponse(content.toString(), responseFormat, parentService);
      return;
    }

    /* Convert the contents into a base64 encoded string... */

    BASE64Encoder encoder = new BASE64Encoder();
    String encodedContent = encoder.encode(content.toString().getBytes());

    /* Build the response string... */

    StringBuffer responseString = new StringBuffer();

    responseString.append("<fileContents>");
    responseString.append(
        "<"
            + SetFileContents.FILENAME_ELEMENT
            + ">"
            + filename
            + "</"
            + SetFileContents.FILENAME_ELEMENT
            + ">");
    responseString.append(
        "<"
            + SetFileContents.ENCODEDCONTENT_ELEMENT
            + ">"
            + encodedContent
            + "</"
            + SetFileContents.ENCODEDCONTENT_ELEMENT
            + ">");
    responseString.append("</fileContents>");

    /* Send the list down to the client... */

    helper.writeResponse(responseString.toString(), responseFormat, parentService);

    return;
  }

  public void setConnection(Connection connection) {
    return;
  }

  public void setInputXML(String xml) {
    return;
  }

  public void setParameter(String parameter, String value) {
    parameters.setProperty(parameter, value);
  }

  public void setProperty(String propertyKey, String propertyValue) {
    if (propertyKey.equals(GetPropertiesFile.START_DIRECTORY)) {
      startDirectory = propertyValue;
    } else if (propertyKey.equals(GetPropertiesFile.VALID_EXTENSIONS)) {
      validExtensions = propertyValue.split(",");
    } else {
      log.warn("The property [" + propertyKey + "] is not supported by the GetFileContents class.");
    }
  }

  public Connection getConnection() {
    return (null);
  }

  public void setPriviledgedHelper(PriviledgedServiceHelper helper) {
    // ignore
  }

  public String getLiteralParametersDefinition() throws UnsupportedOperationException {
    String def =
        "{"
            + "'description' : 'Name of the file to return the contents of',"
            + "'name'        : 'filename',"
            + "'optional'    :  false,"
            + "'type'        : 'string'"
            + "}";

    return (def.replaceAll("'", "\""));
  }

  public String getLiteralReturnsDefinition() throws UnsupportedOperationException {
    String def =
        "{"
            + "'description' : 'Contents of the file',"
            + "'type'        : 'object',"
            + "'properties'  : {"
            + "'fileContents' : {"
            + "'type'       : 'object',"
            + "'properties' : {"
            + "'filename' :  {'type' : 'string'},"
            + "'encodedContent' : {'type' : 'string'}"
            + "}"
            + "}"
            + "}"
            + "}";

    return (def.replaceAll("'", "\""));
  }

  public List getParametersDefinition() throws UnsupportedOperationException {
    throw new UnsupportedOperationException();
  }

  public List getReturnsDefinition() throws UnsupportedOperationException {
    throw new UnsupportedOperationException();
  }
}