public static String getStringFromClob(Clob clob, int bufferSize) {

    if (clob == null) {
      return null;
    }

    StringBuilder string = new StringBuilder();

    BufferedReader bufferedReader = null;

    try {
      bufferedReader = new BufferedReader(clob.getCharacterStream());

      int charactersReadCount = 0;
      char[] buffer = new char[bufferSize];

      while ((charactersReadCount = bufferedReader.read(buffer)) > 0) {
        string.append(buffer, 0, charactersReadCount);
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    } finally {
      try {
        if (bufferedReader != null) {
          bufferedReader.close();
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return string.toString();
  }
  @Override
  public NotificationGroup processSingleResultAllColumns(ResultSet resultSet) {

    try {
      if ((resultSet == null) || resultSet.isClosed()) {
        return null;
      }

      Integer id = resultSet.getInt("ID");
      if (resultSet.wasNull()) id = null;

      String name = resultSet.getString("NAME");
      if (resultSet.wasNull()) name = null;

      String uppercaseName = resultSet.getString("UPPERCASE_NAME");
      if (resultSet.wasNull()) uppercaseName = null;

      String emailAddresses = resultSet.getString("EMAIL_ADDRESSES");
      if (resultSet.wasNull()) emailAddresses = null;

      NotificationGroup notificationGroup =
          new NotificationGroup(id, name, uppercaseName, emailAddresses);

      return notificationGroup;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
  public boolean executeBatchPreparedStatement() {
    try {
      if ((connection_ == null) || (preparedStatement_ == null)) {
        return false;
      }

      if (results_ != null) {
        if (!results_.isClosed()) {
          logger.error(
              "Cannot execute PreparedStatement - DatabaseInterface already has an open ResultSet");
          return false;
        }
      }

      int[] results = preparedStatement_.executeBatch();

      if (results == null || (results.length == 0)) {
        logger.warn("PreparedStatement_ExecuteBatch command did not execute any statements");
      } else {
        for (int resultIndex : results) {
          if (results[resultIndex] == PreparedStatement.EXECUTE_FAILED) {
            logger.error("PreparedStatement executeBatch failed");
            return false;
          }
        }
      }
      return true;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return false;
    }
  }
  public boolean isConnectionValid(int timeoutInSeconds) {

    long startTime = System.currentTimeMillis();

    try {
      if (connection_ == null) {
        return false;
      } else if (!connection_.isValid(timeoutInSeconds)) {
        connection_.close();
        return false;
      } else {
        return true;
      }
    } catch (Exception e) {
      try {
        connection_.close();
      } catch (Exception e2) {
      }

      long timeElapsed = System.currentTimeMillis() - startTime;

      logger.error(
          "Method=IsConnectionValid"
              + ", TimeElapsed="
              + timeElapsed
              + ", Exception="
              + e.toString()
              + System.lineSeparator()
              + StackTrace.getStringFromStackTrace(e));

      return false;
    }
  }
  public List<Integer> getAllNotificationGroupIds() {

    try {

      if (!isConnectionValid()) {
        return new ArrayList<>();
      }

      databaseInterface_.createPreparedStatement(
          NotificationGroupsSql.Select_DistinctNotificationGroupIds, 1000);
      databaseInterface_.executePreparedStatement();

      if (!databaseInterface_.isResultSetValid()) {
        return new ArrayList<>();
      }

      List<Integer> metricGroupIds = new ArrayList<>();

      ResultSet resultSet = databaseInterface_.getResults();

      while (resultSet.next()) {
        Integer id = resultSet.getInt("ID");
        metricGroupIds.add(id);
      }

      return metricGroupIds;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return new ArrayList<>();
    } finally {
      databaseInterface_.cleanupAutomatic();
    }
  }
  public NotificationGroup getNotificationGroupByName(String name) {

    try {

      if (!isConnectionValid()) {
        return null;
      }

      databaseInterface_.createPreparedStatement(
          NotificationGroupsSql.Select_NotificationGroup_ByName, 1);
      databaseInterface_.addPreparedStatementParameters(name);
      databaseInterface_.executePreparedStatement();

      if (!databaseInterface_.isResultSetValid()) {
        return null;
      }

      ResultSet resultSet = databaseInterface_.getResults();

      if (resultSet.next()) {
        NotificationGroup notificationGroup = processSingleResultAllColumns(resultSet);
        return notificationGroup;
      } else {
        return null;
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    } finally {
      databaseInterface_.cleanupAutomatic();
    }
  }
  public ResultSet executePreparedStatement() {
    try {
      if ((connection_ == null) || (preparedStatement_ == null)) {
        return null;
      }

      if (results_ != null) {
        if (!results_.isClosed()) {
          logger.error(
              "Cannot execute PreparedStatement - DatabaseInterface already has an open ResultSet");
          return null;
        }
      }

      setPreparedStatementParameters();

      boolean result = preparedStatement_.execute();

      if (result) {
        results_ = preparedStatement_.getResultSet();
      }

      didPreparedStatementExecuteSuccessfully_ = true;
      return results_;
    } catch (Exception e) {
      didPreparedStatementExecuteSuccessfully_ = false;
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
  private static List<HttpLink> readCustomActionUrls() {

    List<HttpLink> customActionUrls = new ArrayList<>();

    for (int i = 0; i < 1000; i++) {
      String customActionUrlKey = "custom_action_url_" + (i + 1);
      String customActionUrlValue =
          applicationConfiguration_.safeGetString(customActionUrlKey, null);

      if (customActionUrlValue == null) continue;

      try {
        CSVReader reader = new CSVReader(new StringReader(customActionUrlValue));
        List<String[]> csvValuesArray = reader.readAll();

        if ((csvValuesArray != null)
            && !csvValuesArray.isEmpty()
            && (csvValuesArray.get(0) != null)) {
          String[] csvValues = csvValuesArray.get(0);

          if (csvValues.length == 2) {
            String url = csvValues[0];
            String linkText = csvValues[1];

            HttpLink httpLink = new HttpLink(url, linkText);
            customActionUrls.add(httpLink);
          }
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return customActionUrls;
  }
  private static List<GraphiteOutputModule> readGraphiteOutputModules() {

    List<GraphiteOutputModule> graphiteOutputModules = new ArrayList<>();

    for (int i = -1; i < 10000; i++) {
      String graphiteOutputModuleKey = "graphite_output_module_" + (i + 1);
      String graphiteOutputModuleValue =
          applicationConfiguration_.safeGetString(graphiteOutputModuleKey, null);

      if (graphiteOutputModuleValue == null) continue;

      try {
        CSVReader reader = new CSVReader(new StringReader(graphiteOutputModuleValue));
        List<String[]> csvValuesArray = reader.readAll();

        if ((csvValuesArray != null)
            && !csvValuesArray.isEmpty()
            && (csvValuesArray.get(0) != null)) {
          String[] csvValues = csvValuesArray.get(0);

          if (csvValues.length >= 4) {
            boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);
            String host = csvValues[1];
            int port = Integer.valueOf(csvValues[2]);
            int numSendRetryAttempts = Integer.valueOf(csvValues[3]);

            int maxMetricsPerMessage = 1000;
            if (csvValues.length > 4) maxMetricsPerMessage = Integer.valueOf(csvValues[4]);

            boolean sanitizeMetrics = false;
            if (csvValues.length > 5) sanitizeMetrics = Boolean.valueOf(csvValues[5]);

            boolean substituteCharacters = false;
            if (csvValues.length > 6) substituteCharacters = Boolean.valueOf(csvValues[6]);

            String uniqueId = "Graphite-" + (i + 1);

            GraphiteOutputModule graphiteOutputModule =
                new GraphiteOutputModule(
                    isOutputEnabled,
                    host,
                    port,
                    numSendRetryAttempts,
                    maxMetricsPerMessage,
                    sanitizeMetrics,
                    substituteCharacters,
                    uniqueId);

            graphiteOutputModules.add(graphiteOutputModule);
          }
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return graphiteOutputModules;
  }
  protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) {

    if ((request == null) || (response == null)) {
      return;
    }

    response.setContentType("text/html");
    PrintWriter out = null;

    String name = request.getParameter("Name");
    boolean excludeNavbar =
        StringUtilities.isStringValueBooleanTrue(request.getParameter("ExcludeNavbar"));
    String notificationGroup_AlertAssociations =
        getNotificationGroup_AlertAssociations(name, excludeNavbar);

    try {
      StringBuilder htmlBuilder = new StringBuilder();

      StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework();
      String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, "");

      String htmlBody =
          statsAggHtmlFramework.createHtmlBody(
              "<div id=\"page-content-wrapper\">\n"
                  + "<!-- Keep all page content within the page-content inset div! -->\n"
                  + "  <div class=\"page-content inset statsagg_page_content_font\">\n"
                  + "    <div class=\"content-header\"> \n"
                  + "      <div class=\"pull-left content-header-h2-min-width-statsagg\"> <h2> "
                  + PAGE_NAME
                  + " </h2> </div>\n"
                  + "    </div> "
                  + "    <div class=\"statsagg_force_word_wrap\">"
                  + notificationGroup_AlertAssociations
                  + "    </div>\n"
                  + "  </div>\n"
                  + "</div>\n",
              excludeNavbar);

      htmlBuilder
          .append("<!DOCTYPE html>\n<html>\n")
          .append(htmlHeader)
          .append(htmlBody)
          .append("</html>");

      Document htmlDocument = Jsoup.parse(htmlBuilder.toString());
      String htmlFormatted = htmlDocument.toString();
      out = response.getWriter();
      out.println(htmlFormatted);
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
Example #11
0
 public boolean isResultSetValid() {
   try {
     if ((results_ == null) || results_.isClosed()) {
       return false;
     } else {
       return true;
     }
   } catch (Exception e) {
     logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
     return false;
   }
 }
Example #12
0
  public Statement createStatement() {
    try {
      if ((connection_ == null) || connection_.isClosed()) {
        return null;
      }

      statement_ = connection_.createStatement();
      return statement_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
Example #13
0
  public Statement setStatement(Statement statement) {
    try {
      if (connection_ == null) {
        return null;
      }

      statement_ = statement;
      return statement_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
Example #14
0
  public PreparedStatement setPreparedStatement(PreparedStatement preparedStatement) {
    try {
      if (connection_ == null) {
        return null;
      }

      preparedStatement_ = preparedStatement;
      preparedStatementParameters_ = new ArrayList<>();
      return preparedStatement_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
  private static List<OpenTsdbHttpOutputModule> readOpenTsdbHttpOutputModules() {

    List<OpenTsdbHttpOutputModule> openTsdbHttpOutputModules = new ArrayList<>();

    for (int i = -1; i < 10000; i++) {
      String openTsdbHttpOutputModuleKey = "opentsdb_http_output_module_" + (i + 1);
      String openTsdbHttpOutputModuleValue =
          applicationConfiguration_.safeGetString(openTsdbHttpOutputModuleKey, null);

      if (openTsdbHttpOutputModuleValue == null) continue;

      try {
        CSVReader reader = new CSVReader(new StringReader(openTsdbHttpOutputModuleValue));
        List<String[]> csvValuesArray = reader.readAll();

        if ((csvValuesArray != null)
            && !csvValuesArray.isEmpty()
            && (csvValuesArray.get(0) != null)) {
          String[] csvValues = csvValuesArray.get(0);

          if (csvValues.length >= 4) {
            boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);
            String url = csvValues[1];
            int numSendRetryAttempts = Integer.valueOf(csvValues[2]);
            int maxMetricsPerMessage = Integer.valueOf(csvValues[3]);

            boolean sanitizeMetrics = false;
            if (csvValues.length > 4) sanitizeMetrics = Boolean.valueOf(csvValues[4]);

            String uniqueId = "OpenTSDB-HTTP-" + (i + 1);

            OpenTsdbHttpOutputModule openTsdbHttpOutputModule =
                new OpenTsdbHttpOutputModule(
                    isOutputEnabled,
                    url,
                    numSendRetryAttempts,
                    maxMetricsPerMessage,
                    sanitizeMetrics,
                    uniqueId);
            openTsdbHttpOutputModules.add(openTsdbHttpOutputModule);
          }
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return openTsdbHttpOutputModules;
  }
Example #16
0
  public PreparedStatement createPreparedStatement(String sql, int fetchSize) {
    try {
      if ((connection_ == null) || connection_.isClosed()) {
        return null;
      }

      preparedStatement_ = connection_.prepareStatement(sql);
      preparedStatement_.setFetchSize(fetchSize);
      preparedStatementParameters_ = new ArrayList<>();
      return preparedStatement_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
Example #17
0
  public PreparedStatement createPreparedStatement(
      String sql, List<Object> preparedStatementParameters) {
    try {
      if ((connection_ == null) || connection_.isClosed()) {
        return null;
      }

      preparedStatement_ = connection_.prepareStatement(sql);
      preparedStatementParameters_ = preparedStatementParameters;

      return preparedStatement_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    }
  }
Example #18
0
  public List<Object> addPreparedStatementParameters(List<Object> objects) {
    try {
      if ((connection_ == null)
          || (preparedStatement_ == null)
          || (preparedStatementParameters_ == null)
          || (objects == null)) {
        return new ArrayList<>();
      }

      preparedStatementParameters_.addAll(objects);

      return preparedStatementParameters_;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return new ArrayList<>();
    }
  }
Example #19
0
  public void close() {

    if (isTransactionOpen_ == true) {
      logger.warn(
          "Closing a DatabaseInterface with an open transaction. Rolling back transaction...");
      logger.warn(StackTrace.getStringFromStackTrace(Thread.currentThread().getStackTrace()));
      rollback();
    }

    if (preparedStatementParameters_ != null) {
      preparedStatementParameters_.clear();
      preparedStatementParameters_ = null;
    }

    didPreparedStatementExecuteSuccessfully_ = null;

    DatabaseCleanup.cleanup(this);
  }
Example #20
0
  public void rollback() {

    if (connection_ == null) {
      return;
    }

    try {
      if (!connection_.getAutoCommit()) {
        connection_.rollback();
      } else {
        logger.debug("Cannot rollback when Auto-Commit is enabled");
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    } finally {
      isTransactionOpen_ = false;
    }
  }
  private static List<InfluxdbV1HttpOutputModule> readInfluxdbV1HttpOutputModules() {

    List<InfluxdbV1HttpOutputModule> influxdbV1HttpOutputModules = new ArrayList<>();

    for (int i = -1; i < 10000; i++) {
      String influxdbV1HttpOutputModuleKey = "influxdb_v1_output_module_" + (i + 1);
      String influxdbV1HttpOutputModuleValue =
          applicationConfiguration_.safeGetString(influxdbV1HttpOutputModuleKey, null);

      if (influxdbV1HttpOutputModuleValue == null) continue;

      try {
        CSVReader reader = new CSVReader(new StringReader(influxdbV1HttpOutputModuleValue));
        List<String[]> csvValuesArray = reader.readAll();

        if ((csvValuesArray != null)
            && !csvValuesArray.isEmpty()
            && (csvValuesArray.get(0) != null)) {
          String[] csvValues = csvValuesArray.get(0);

          if (csvValues.length == 4) {
            boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);
            String url = csvValues[1];
            int numSendRetryAttempts = Integer.valueOf(csvValues[2]);
            int maxMetricsPerMessage = Integer.valueOf(csvValues[3]);

            String uniqueId = "InfluxDB-V1-" + (i + 1);

            InfluxdbV1HttpOutputModule influxdbV1HttpOutputModule =
                new InfluxdbV1HttpOutputModule(
                    isOutputEnabled, url, numSendRetryAttempts, maxMetricsPerMessage, uniqueId);

            influxdbV1HttpOutputModules.add(influxdbV1HttpOutputModule);
          }
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return influxdbV1HttpOutputModules;
  }
Example #22
0
  public void setPreparedStatementParameters() {

    if ((preparedStatement_ == null) || (preparedStatementParameters_ == null)) {
      logger.warn(
          "Can't set preparedStatementParameters - preparedStatementParameters or preparedStatement is null");
      return;
    }

    try {
      int index = 1;

      for (Object object : preparedStatementParameters_) {
        int incrementedIndex = setPreparedStatementParameter(object, index);
        index = incrementedIndex;
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return;
    }
  }
Example #23
0
  public void beginTransaction() {

    if (connection_ == null) {
      return;
    }

    try {
      if (connection_.getAutoCommit()) {
        logger.warn("Cannot being a transaction when autocommit mode is enabled");
      } else {
        if (!isTransactionOpen_) {
          isTransactionOpen_ = true;
        } else {
          logger.debug(
              "Request to being a transaction on a DatabaseInterface when transaction is already open");
        }
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
  }
  public List<String> getNotificationGroupNames(String filter, int resultSetLimit) {

    try {

      if (!isConnectionValid()) {
        return new ArrayList<>();
      }

      List<String> notificationGroupNames = new ArrayList<>();

      databaseInterface_.createPreparedStatement(
          NotificationGroupsSql.Select_NotificationGroup_Names_OrderByName, 1000);
      databaseInterface_.addPreparedStatementParameters("%" + filter + "%");
      databaseInterface_.executePreparedStatement();

      if (!databaseInterface_.isResultSetValid()) {
        return new ArrayList<>();
      }

      ResultSet resultSet = databaseInterface_.getResults();

      int rowCounter = 0;
      while (resultSet.next() && (rowCounter < resultSetLimit)) {
        String name = resultSet.getString("NAME");
        if (resultSet.wasNull()) name = null;

        if (name != null) {
          notificationGroupNames.add(name);
          rowCounter++;
        }
      }

      return notificationGroupNames;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return new ArrayList<>();
    } finally {
      databaseInterface_.cleanupAutomatic();
    }
  }
  public Map<Integer, String> getNotificationGroupNames_ById() {

    try {

      if (!isConnectionValid()) {
        return new HashMap<>();
      }

      Map<Integer, String> notificationGroupNames_ById = new HashMap<>();

      databaseInterface_.createPreparedStatement(
          NotificationGroupsSql.Select_AllNotificationGroup_IdsAndNames, 1000);
      databaseInterface_.executePreparedStatement();

      if (!databaseInterface_.isResultSetValid()) {
        return new HashMap<>();
      }

      ResultSet resultSet = databaseInterface_.getResults();

      while (resultSet.next()) {
        Integer id = resultSet.getInt("ID");
        if (resultSet.wasNull()) id = null;

        String name = resultSet.getString("NAME");
        if (resultSet.wasNull()) name = null;

        if ((id != null) && (name != null)) notificationGroupNames_ById.put(id, name);
      }

      return notificationGroupNames_ById;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return new HashMap<>();
    } finally {
      databaseInterface_.cleanupAutomatic();
    }
  }
  protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) {

    if ((request == null) || (response == null)) {
      return;
    }

    response.setContentType("text/html");
    PrintWriter out = null;

    try {
      String html = buildNotificationGroupsHtml();

      Document htmlDocument = Jsoup.parse(html);
      String htmlFormatted = htmlDocument.toString();
      out = response.getWriter();
      out.println(htmlFormatted);
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
  private void cloneNotificationGroup(String notificationGroupName) {

    if (notificationGroupName == null) {
      return;
    }

    try {
      NotificationGroupsDao notificationGroupsDao = new NotificationGroupsDao(false);
      NotificationGroup notificationGroup =
          notificationGroupsDao.getNotificationGroupByName(notificationGroupName);
      List<NotificationGroup> allNotificationGroups =
          notificationGroupsDao.getAllDatabaseObjectsInTable();
      notificationGroupsDao.close();

      if ((notificationGroup != null) && (notificationGroup.getName() != null)) {
        Set<String> allNotificationGroupNames = new HashSet<>();
        for (NotificationGroup currentNotificationGroup : allNotificationGroups) {
          if (currentNotificationGroup.getName() != null)
            allNotificationGroupNames.add(currentNotificationGroup.getName());
        }

        NotificationGroup clonedNotificationGroup = NotificationGroup.copy(notificationGroup);
        clonedNotificationGroup.setId(-1);
        String clonedAlterName =
            StatsAggHtmlFramework.createCloneName(
                notificationGroup.getName(), allNotificationGroupNames);
        clonedNotificationGroup.setName(clonedAlterName);
        clonedNotificationGroup.setUppercaseName(clonedAlterName.toUpperCase());

        NotificationGroupsLogic notificationGroupsLogic = new NotificationGroupsLogic();
        notificationGroupsLogic.alterRecordInDatabase(clonedNotificationGroup);
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
  }
Example #28
0
  // this method is a work in progress. additional functionality will be added as needed.
  private int setPreparedStatementParameter(Object object, int index) {

    if ((preparedStatement_ == null) || (preparedStatementParameters_ == null)) {
      logger.warn(
          "Can't set preparedStatementParameters - preparedStatementParameters or preparedStatement is null");
      return -1;
    }

    try {
      if (object == null) {
        preparedStatement_.setObject(index++, null);
      } else if (object instanceof BigDecimal) {
        preparedStatement_.setBigDecimal(index++, (BigDecimal) object);
      } else if (object instanceof Blob) {
        preparedStatement_.setBlob(index++, (Blob) object);
      } else if (object instanceof Boolean) {
        preparedStatement_.setBoolean(index++, (Boolean) object);
      } else if (object instanceof Byte) {
        preparedStatement_.setByte(index++, (Byte) object);
      } else if (object instanceof byte[]) {
        preparedStatement_.setBytes(index++, (byte[]) object);
      } else if (object instanceof Clob) {
        preparedStatement_.setClob(index++, (Clob) object);
      } else if (object instanceof Double) {
        preparedStatement_.setDouble(index++, (Double) object);
      } else if (object instanceof Float) {
        preparedStatement_.setFloat(index++, (Float) object);
      } else if (object instanceof Integer) {
        preparedStatement_.setInt(index++, (Integer) object);
      } else if (object instanceof List) {
        for (Object listObject : (List) object) {
          setPreparedStatementParameter(listObject, index++);
        }
      } else if (object instanceof Long) {
        preparedStatement_.setLong(index++, (Long) object);
      } else if (object instanceof Short) {
        preparedStatement_.setShort(index++, (Short) object);
      } else if (object instanceof String) {
        preparedStatement_.setString(index++, (String) object);
      } else if (object instanceof java.sql.Timestamp) {
        preparedStatement_.setTimestamp(index++, (java.sql.Timestamp) object);
      } else if (object instanceof java.sql.Date) {
        preparedStatement_.setDate(index++, (java.sql.Date) object);
      } else if (object instanceof java.util.Date) {
        java.util.Date tempDate = (java.util.Date) object;
        java.sql.Date dateSql = new java.sql.Date(tempDate.getTime());
        preparedStatement_.setDate(index++, dateSql);
      } else {
        if (object instanceof Object) {
        } else {
          logger.warn(
              "Setting PreparedStatement parameter to 'object' type when object is not an object type");
        }

        preparedStatement_.setObject(index++, object);
      }

      return index;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return -1;
    }
  }
  public JSONObject getNotificationGroups(int offset, int pageSize) {
    logger.debug("getNotificationGroups");
    List<Object> parametersList = new ArrayList<>(2);

    JSONArray notificationGroupsList = new JSONArray();
    JSONObject notificationGroupsJson = new JSONObject();
    int alertsCount = 0;

    try {
      if (!isConnectionValid()) {
        return null;
      }

      if ((offset == 0) && (pageSize == 0)) {
        notificationGroupsJson.put("notificationgroups", notificationGroupsList);
        notificationGroupsJson.put("count", alertsCount);
        return notificationGroupsJson;
      }

      parametersList.add(offset);
      parametersList.add(pageSize);

      if (DatabaseConfiguration.getType() == DatabaseConfiguration.MYSQL) {
        databaseInterface_.createPreparedStatement(
            NotificationGroupsSql.Select_NotificationGroups_ByPageNumberAndPageSize_MySQL,
            pageSize);
      } else {
        databaseInterface_.createPreparedStatement(
            NotificationGroupsSql.Select_NotificationGroups_ByPageNumberAndPageSize_Derby,
            pageSize);
      }
      databaseInterface_.addPreparedStatementParameters(parametersList);

      databaseInterface_.executePreparedStatement();

      if (!databaseInterface_.isResultSetValid()) {
        logger.debug("Invalid resultset");
        return null;
      }

      ResultSet resultSet = databaseInterface_.getResults();

      while (resultSet.next()) {
        JSONObject alert = new JSONObject();
        alert.put("name", resultSet.getString("NAME"));
        alert.put("id", resultSet.getString("ID"));
        notificationGroupsList.add(alert);
        alertsCount++;
      }

      notificationGroupsJson.put("notificationgroups", notificationGroupsList);
      notificationGroupsJson.put("count", alertsCount);

      return notificationGroupsJson;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return null;
    } finally {
      databaseInterface_.cleanupAutomatic();
    }
  }
  private static boolean setApplicationConfigurationValues() {

    try {
      flushTimeAgg_ = applicationConfiguration_.safeGetInteger("flush_time_agg", 10000);
      debugModeEnabled_ = applicationConfiguration_.safeGetBoolean("debug_mode_enabled", false);

      // graphite output configuration
      graphiteOutputModules_.addAll(readGraphiteOutputModules());

      // opentsdb telnet output configuration
      openTsdbTelnetOutputModules_.addAll(readOpenTsdbTelnetOutputModules());

      // opentsdb http output configuration
      openTsdbHttpOutputModules_.addAll(readOpenTsdbHttpOutputModules());

      // opentsdb configuration
      influxdbV1HttpOutputModules_.addAll(readInfluxdbV1HttpOutputModules());

      // listener config
      statsdTcpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean("statsd_tcp_listener_enabled", true);
      statsdTcpListenerPort_ =
          applicationConfiguration_.safeGetInt("statsd_tcp_listener_port", 8125);
      statsdUdpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean("statsd_udp_listener_enabled", true);
      statsdUdpListenerPort_ =
          applicationConfiguration_.safeGetInt("statsd_udp_listener_port", 8125);
      graphiteAggregatorTcpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_aggregator_tcp_listener_enabled", true);
      graphiteAggregatorTcpListenerPort_ =
          applicationConfiguration_.safeGetInt("graphite_aggregator_tcp_listener_port", 22003);
      graphiteAggregatorUdpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_aggregator_udp_listener_enabled", true);
      graphiteAggregatorUdpListenerPort_ =
          applicationConfiguration_.safeGetInt("graphite_aggregator_udp_listener_port", 22003);
      graphitePassthroughTcpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_passthrough_tcp_listener_enabled", true);
      graphitePassthroughTcpListenerPort_ =
          applicationConfiguration_.safeGetInt("graphite_passthrough_tcp_listener_port", 2003);
      graphitePassthroughUdpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_passthrough_udp_listener_enabled", true);
      graphitePassthroughUdpListenerPort_ =
          applicationConfiguration_.safeGetInt("graphite_passthrough_udp_listener_port", 2003);
      openTsdbTcpTelnetListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean("opentsdb_tcp_telnet_listener_enabled", true);
      openTsdbTcpTelnetListenerPort_ =
          applicationConfiguration_.safeGetInt("opentsdb_tcp_telnet_listener_port", 4242);
      openTsdbHttpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean("opentsdb_http_listener_enabled", true);
      openTsdbHttpListenerPort_ =
          applicationConfiguration_.safeGetInt("opentsdb_http_listener_port", 4243);
      influxdbHttpListenerEnabled_ =
          applicationConfiguration_.safeGetBoolean("influxdb_http_listener_enabled", true);
      influxdbHttpListenerPort_ =
          applicationConfiguration_.safeGetInt("influxdb_http_listener_port", 8086);

      // metric naming config
      globalMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean("global_metric_name_prefix_enabled", false);
      globalMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString("global_metric_name_prefix_value", "statsagg");
      globalAggregatedMetricsSeparatorString_ =
          applicationConfiguration_.safeGetString(
              "global_aggregated_metrics_separator_string", ".");
      statsdMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean("statsd_metric_name_prefix_enabled", false);
      statsdMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString("statsd_metric_name_prefix_value", "stats");
      statsdMetricNameSuffixEnabled_ =
          applicationConfiguration_.safeGetBoolean("statsd_metric_name_suffix_enabled", false);
      statsdMetricNameSuffixValue_ =
          applicationConfiguration_.safeGetString("statsd_metric_name_suffix_value", "");
      statsdCounterMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "statsd_counter_metric_name_prefix_enabled", false);
      statsdCounterMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString(
              "statsd_counter_metric_name_prefix_value", "counters");
      statsdGaugeMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "statsd_gauge_metric_name_prefix_enabled", false);
      statsdGaugeMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString(
              "statsd_gauge_metric_name_prefix_value", "gauges");
      statsdTimerMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "statsd_timer_metric_name_prefix_enabled", false);
      statsdTimerMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString(
              "statsd_timer_metric_name_prefix_value", "timers");
      statsdSetMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean("statsd_set_metric_name_prefix_enabled", false);
      statsdSetMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString("statsd_set_metric_name_prefix_value", "sets");
      graphiteAggregatorMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_aggregator_metric_name_prefix_enabled", false);
      graphiteAggregatorMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString(
              "graphite_aggregator_metric_name_prefix_value", "graphite-agg");
      graphitePassthroughMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean(
              "graphite_passthrough_metric_name_prefix_enabled", false);
      graphitePassthroughMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString(
              "graphite_passthrough_metric_name_prefix_value", "graphite");
      openTsdbMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean("opentsdb_metric_name_prefix_enabled", false);
      openTsdbMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString("opentsdb_metric_name_prefix_value", "opentsdb");
      influxdbMetricNamePrefixEnabled_ =
          applicationConfiguration_.safeGetBoolean("influxdb_metric_name_prefix_enabled", false);
      influxdbMetricNamePrefixValue_ =
          applicationConfiguration_.safeGetString("influxdb_metric_name_prefix_value", "influxdb");
      influxdbIncludeDatabaseNameInNonNativeOutput_ =
          applicationConfiguration_.safeGetBoolean(
              "influxdb_include_database_name_in_non_native_output", true);

      // statsd specific variables
      statsdCounterSendZeroOnInactive_ =
          applicationConfiguration_.safeGetBoolean("statsd_counter_send_0_on_inactive", true);
      statsdTimerSendZeroOnInactive_ =
          applicationConfiguration_.safeGetBoolean("statsd_timer_send_0_on_inactive", true);
      statsdGaugeSendPreviousValue_ =
          applicationConfiguration_.safeGetBoolean("statsd_gauge_send_previous_value", true);
      statsdSetSendZeroOnInactive_ =
          applicationConfiguration_.safeGetBoolean("statsd_set_send_0_on_inactive", true);
      statsdNthPercentiles_ =
          new StatsdNthPercentiles(
              applicationConfiguration_.safeGetString("statsd_nth_percentiles", "90"));
      statsdHistogramConfigurations_ =
          readStatsdHistogramConfiguration(
              applicationConfiguration_.safeGetString("statsd_histograms", null));
      statsdUseLegacyNameSpacing_ =
          applicationConfiguration_.safeGetBoolean("statsd_use_legacy_name_spacing", false);
      statsdPersistGauges_ =
          applicationConfiguration_.safeGetBoolean("statsd_persist_gauges", true);

      // influxdb specific variables
      influxdbDefaultDatabaseName_ =
          applicationConfiguration_.safeGetString("influxdb_default_database_name", "statsagg");
      influxdbDefaultDatabaseUsername_ =
          applicationConfiguration_.safeGetString("influxdb_default_database_username", "statsagg");
      influxdbDefaultDatabasePassword_ =
          applicationConfiguration_.safeGetString("influxdb_default_database_password", "statsagg");
      if ((influxdbDefaultDatabaseUsername_ != null) && (influxdbDefaultDatabasePassword_ != null))
        influxdbDefaultDatabaseHttpBasicAuthValue_ =
            "Basic "
                + Base64.encodeBase64String(
                    (influxdbDefaultDatabaseUsername_ + ":" + influxdbDefaultDatabasePassword_)
                        .getBytes("UTF-8"));
      else influxdbDefaultDatabaseHttpBasicAuthValue_ = null;

      // alerting variables
      alertRoutineEnabled_ =
          applicationConfiguration_.safeGetBoolean("alert_routine_enabled", true);
      alertRoutineInterval_ =
          applicationConfiguration_.safeGetInteger("alert_routine_interval", 5000);
      alertSendEmailEnabled_ =
          applicationConfiguration_.safeGetBoolean("alert_send_email_enabled", false);
      alertMaxMetricsInEmail_ =
          applicationConfiguration_.safeGetInteger("alert_max_metrics_in_email", 100);
      alertOutputStatus_ = applicationConfiguration_.safeGetBoolean("alert_output_status", true);
      alertOutputStatusMetricPrefix_ =
          applicationConfiguration_.safeGetString(
              "alert_output_status_metric_prefix", "StatsAgg-Alerts");
      alertStatsAggLocation_ =
          applicationConfiguration_.safeGetString("alert_statsagg_location", "");
      alertWaitTimeAfterRestart_ =
          applicationConfiguration_.safeGetInteger("alert_wait_time_after_restart", 120000);

      alertSmtpHost_ = applicationConfiguration_.safeGetString("alert_smtp_host", "127.0.0.1");
      alertSmtpPort_ = applicationConfiguration_.safeGetInteger("alert_smtp_port", 25);
      alertSmtpConnectionTimeout_ =
          applicationConfiguration_.safeGetInteger("alert_smtp_connection_timeout", 15000);
      alertSmtpUsername_ = applicationConfiguration_.safeGetString("alert_smtp_username", "");
      alertSmtpPassword_ = applicationConfiguration_.safeGetString("alert_smtp_password", "");
      alertSmtpUseSslTls_ =
          applicationConfiguration_.safeGetBoolean("alert_smtp_use_ssl_tls", false);
      alertSmtpUseStartTls_ =
          applicationConfiguration_.safeGetBoolean("alert_smtp_use_starttls", false);
      alertSmtpFromAddress_ =
          applicationConfiguration_.safeGetString("alert_smtp_from_address", "*****@*****.**");
      alertSmtpFromName_ =
          applicationConfiguration_.safeGetString("alert_smtp_from_name", "StatsAgg");

      // website custominzation variables
      customActionUrls_.addAll(readCustomActionUrls());

      // advanced
      outputModuleMaxConnectTime_ =
          applicationConfiguration_.safeGetInteger("output_module_max_connect_time", 3000);
      outputModuleMaxReadTime_ =
          applicationConfiguration_.safeGetInteger("output_module_max_read_time", 120000);
      outputModuleMaxConcurrentThreads_ =
          applicationConfiguration_.safeGetInteger("output_module_max_concurrent_threads", 25);
      outputModuleMaxConcurrentThreadsForSingleModule_ =
          applicationConfiguration_.safeGetInteger(
              "output_module_max_concurrent_threads_for_single_module", 10);

      return true;
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      return false;
    }
  }