Package private for testability

@param pSqlException PostgreSQL exception
@return translated validation exception
480796
MolgenisValidationException translateForeignKeyViolation(PSQLException pSqlException) {
    ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
    String tableName = serverErrorMessage.getTable();
    String detailMessage = serverErrorMessage.getDetail();
    Matcher m = Pattern.compile("\\((.*?)\\)").matcher(detailMessage);
    if (!m.find()) {
      LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
      throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
    }
    String colName = m.group(1);
    if (!m.find()) {
      LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
      throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
    }
    String value = m.group(1);

    String constraintViolationMessageTemplate;
    String attrName;
    if (detailMessage.contains("still referenced from")) {
      // ERROR: update or delete on table "x" violates foreign key constraint "y" on table "z"
      // Detail: Key (k)=(v) is still referenced from table "x".
      constraintViolationMessageTemplate =
          "Value '%s' for attribute '%s' is referenced by entity '%s'.";
      String refTableName = getRefTableFromForeignKeyPsqlException(pSqlException);
      attrName = tryGetAttributeName(refTableName, colName).orElse(TOKEN_UNKNOWN);
    } else {
      // ERROR: insert or update on table "x" violates foreign key constraint "y"
      // Detail: Key (k)=(v) is not present in table "z".
      constraintViolationMessageTemplate =
          "Unknown xref value '%s' for attribute '%s' of entity '%s'.";
      attrName = tryGetAttributeName(tableName, colName).orElse(TOKEN_UNKNOWN);
    }
    ConstraintViolation constraintViolation =
        new ConstraintViolation(
            format(
                constraintViolationMessageTemplate,
                value,
                attrName,
                tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
            null);
    return new MolgenisValidationException(singleton(constraintViolation));
  }
1334820
public void receiveEOF() throws SQLException, IOException {
    int c = pgInput.read();
    if (c < 0) {
      return;
    }
    throw new PSQLException(GT.tr("Expected an EOF from server, got: {0}", c),
        PSQLState.COMMUNICATION_ERROR);
  }
197755
@Override
    public void isValid() throws Exception {
        if (numStmnts() >= 2) {
            if (primaryJoinableHooks.size() > 0) {
                for (String joinField:primaryJoinableHooks) {
                    if (joinField.equals("timestamp")) {// timestamp is implicitly present in the result.
                        continue;
                    }
                    for (QueryMeta query: getAllStmnts()) {
                        boolean isPresent = false;
                        if (query instanceof BaseAggQueryMeta) {// Since BaseAggQueryMeta is also a PlainDimQueryMeta we go with former first.
                            for (AggItem item:((BaseAggQueryMeta)query).aggregations) {
                                if (joinField.equals(item.fieldName) || (item.asName != null && joinField.equals(item.asName))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (query instanceof PlainDimQueryMeta) {
                            Map<String, String> dims = ((PlainDimQueryMeta)query).fetchDimensions;
                            for (Map.Entry<String, String> entry :dims.entrySet()) {
                                if (joinField.equals(entry.getKey()) || (entry.getValue() != null && joinField.equals(entry.getValue()))) {
                                    isPresent = true;
                                }
                            }
                        }
                        if (!isPresent) {
                            String error = joinField + " mentioned in the composite key should appear in all the data sources being queried and joined.";
                            throw new Exception(error);
                        }
                    }
                }
            } else {
                String error = "Need atleast one field to join on";
                throw new Exception(error);
            }
        }
    }
590454
MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) {
    ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
    String tableName = serverErrorMessage.getTable();
    String message = serverErrorMessage.getMessage();
    Matcher matcher =
        Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint")
            .matcher(message);
    boolean matches = matcher.matches();
    if (matches) {
      // exception message when adding data that does not match constraint
      String columnName = matcher.group(1);

      EntityTypeDescription entityTypeDescription =
          entityTypeRegistry.getEntityTypeDescription(tableName);
      entityTypeDescription.getAttributeDescriptionMap().get(columnName);

      ConstraintViolation constraintViolation =
          new ConstraintViolation(
              format(
                  "The attribute '%s' of entity '%s' can not be null.",
                  tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
                  tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
              null);
      return new MolgenisValidationException(singleton(constraintViolation));
    } else {
      // exception message when applying constraint on existing data
      matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message);
      matches = matcher.matches();
      if (!matches) {
        throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
      }
      String columnName = matcher.group(1);

      ConstraintViolation constraintViolation =
          new ConstraintViolation(
              format(
                  "The attribute '%s' of entity '%s' contains null values.",
                  tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN),
                  tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)),
              null);
      return new MolgenisValidationException(singleton(constraintViolation));
    }
  }
251545
public static void assertTrueOrInvalidGlobalTypeApdaterException(boolean expression,
			SQLiteDatabaseSchema sqLiteDatabaseSchema, String typeAdapter, String typeAdapter2) {
		if (!expression) {
			String msg = String.format(
					"In data source '%s', there are two or more global type adapter that cover type '%s': '%s' and '%s'",
					sqLiteDatabaseSchema.getElement().getQualifiedName(),
					TypeAdapterHelper.detectSourceType(typeAdapter), typeAdapter, typeAdapter2);
			throw (new InvalidDefinition(msg));
		}
	}
311778
public final String evSqlVl(
    final String pNm) throws ExceptionWithCode {
    Object val = evObjVl(pNm);
    if (val == null) {
      return "null";
    } else {
      return val.toString();
    }
  }
883302
MolgenisValidationException translateDependentObjectsStillExist(PSQLException pSqlException) {
    ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
    String detail = serverErrorMessage.getDetail();
    Matcher matcher =
        Pattern.compile(
                "constraint (.+) on table \"?([^\"]+)\"? depends on table \"?([^\"]+)\"?\n?")
            .matcher(detail);

    Map<String, Set<String>> entityTypeDependencyMap = new LinkedHashMap<>();
    while (matcher.find()) {
      String tableName = matcher.group(2);
      String dependentTableName = matcher.group(3);

      String entityTypeName = tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN);
      String dependentEntityTypeName =
          tryGetEntityTypeName(dependentTableName).orElse(TOKEN_UNKNOWN);
      Set<String> dependentTableNames =
          entityTypeDependencyMap.computeIfAbsent(
              dependentEntityTypeName, k -> new LinkedHashSet<>());
      dependentTableNames.add(entityTypeName);
    }

    if (entityTypeDependencyMap.isEmpty()) // no matches
    {
      LOG.error(ERROR_TRANSLATING_POSTGRES_EXC_MSG, pSqlException);
      throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException);
    }

    Set<ConstraintViolation> constraintViolations =
        entityTypeDependencyMap
            .entrySet()
            .stream()
            .map(
                entry -> {
                  String message;
                  if (entry.getValue().size() == 1) {
                    message =
                        format(
                            "Cannot delete entity '%s' because entity '%s' depends on it.",
                            entry.getKey(), entry.getValue().iterator().next());
                  } else {
                    message =
                        format(
                            "Cannot delete entity '%s' because entities '%s' depend on it.",
                            entry.getKey(), entry.getValue().stream().collect(joining(", ")));
                  }
                  return new ConstraintViolation(message, null);
                })
            .collect(toCollection(LinkedHashSet::new));

    return new MolgenisValidationException(constraintViolations);
  }
46366
public static void assertTrueOrUnknownPropertyInJQLException(boolean expression, JQLContext method,
			String columnName) {
		if (!expression) {
			throw (new UnknownPropertyInJQLException(method, columnName));
		}

	}
189924
public static SQLException unwrapSQLException(Throwable throwable) {
        if (throwable == null) {
            return null;
        } else if (throwable instanceof SQLException) {
            return (SQLException) throwable;
        } else if (throwable.getCause() != null) {
            // recursive call to unwrap the cause
            return unwrapSQLException(throwable.getCause());
        } else {
            // didn't find any SQLException in the cause stack
            return null;
        }
    }
1332465
public final String evalSqlValue(
    final String pName) throws ExceptionWithCode {
    Object value = evalObjectValue(pName);
    if (value == null) {
      return "null";
    } else {
      return value.toString();
    }
  }
119782
public static String exceptionList(Throwable ex) { 
        StringBuilder sb = new StringBuilder();

        sb.append("<=================================>");
        sb.append("Exception Message -> ");
        sb.append(ex.getMessage());
        sb.append(nl);
        if (ex instanceof ResourceException) {
            sb.append("  ResourceException Error Code -> ");
            sb.append(((ResourceException) ex).getErrorCode());
            sb.append(nl);
        }
        if (ex instanceof SQLException) {
            sb.append("  SQLException  Error Code -> ");
            sb.append(((SQLException) ex).getErrorCode());
            sb.append(nl);
            sb.append("  SQLException  SQLState -> ");
            sb.append(((SQLException) ex).getSQLState());
            sb.append(nl);
        }
        // Get stack trace of current exception
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        sb.append(sw.getBuffer());
        sb.append("<=================================>");

        // If exception supports linked exceptions, get linked exception
        Throwable ex2 = null;
        ex2 = ex.getCause();

        // If we got a linked exception, recursively call this method
        if (ex2 != null) {
            sb.append("Next Linked Exception:" + nl);
            sb.append(exceptionList(ex2));
        }

        return sb.toString();

    }
1012570
private void onValidateTables(List<TableInfo> tableInfos, KsDef ksDef) throws Exception
    {
        cassandra_client.set_keyspace(ksDef.getName());
        for (TableInfo tableInfo : tableInfos)
        {
            if (isCql3Enabled(tableInfo) && !tableInfo.getType().equals(Type.SUPER_COLUMN_FAMILY.name()))
            {
                CqlMetadata metadata = new CqlMetadata();
                Map<ByteBuffer, String> name_types = new HashMap<ByteBuffer, String>();
                Map<ByteBuffer, String> value_types = new HashMap<ByteBuffer, String>();
                List<ColumnInfo> columnInfos = tableInfo.getColumnMetadatas();

                List<EmbeddedColumnInfo> compositeColumns = tableInfo.getEmbeddedColumnMetadatas();
                if (compositeColumns != null && !compositeColumns.isEmpty())
                {
                    EmbeddableType embeddableType = compositeColumns.get(0).getEmbeddable();
                    for (ColumnInfo columnInfo : compositeColumns.get(0).getColumns())
                    {
                        name_types
                                .put(ByteBufferUtil.bytes(columnInfo.getColumnName()), UTF8Type.class.getSimpleName());
                        value_types.put(ByteBufferUtil.bytes(columnInfo.getColumnName()),
                                CassandraValidationClassMapper.getValidationClassInstance(columnInfo.getType(), true)
                                        .getName());
                    }

                }
                else
                {
                    name_types.put(ByteBufferUtil.bytes(tableInfo.getIdColumnName()), UTF8Type.class.getSimpleName());
                    value_types.put(ByteBufferUtil.bytes(tableInfo.getIdColumnName()), CassandraValidationClassMapper
                            .getValidationClassInstance(tableInfo.getTableIdType(), true).getName());
                }

                for (ColumnInfo info : columnInfos)
                {
                    name_types.put(ByteBufferUtil.bytes(info.getColumnName()), UTF8Type.class.getSimpleName());
                    value_types.put(ByteBufferUtil.bytes(info.getColumnName()), CassandraValidationClassMapper
                            .getValidationClassInstance(info.getType(), true).getName());
                }

                for (CollectionColumnInfo info : tableInfo.getCollectionColumnMetadatas())
                {
                    name_types
                            .put(ByteBufferUtil.bytes(info.getCollectionColumnName()), UTF8Type.class.getSimpleName());
                    value_types.put(ByteBufferUtil.bytes(info.getCollectionColumnName()),
                            CassandraValidationClassMapper.getValueTypeName(info.getType(), info.getGenericClasses(),
                                    true));
                }

                metadata.setDefault_name_type(UTF8Type.class.getSimpleName());
                metadata.setDefault_value_type(UTF8Type.class.getSimpleName());
                metadata.setName_types(name_types);
                metadata.setValue_types(value_types);
                CQLTranslator translator = new CQLTranslator();
                final String describeTable = "select * from ";
                StringBuilder builder = new StringBuilder(describeTable);
                translator.ensureCase(builder, tableInfo.getTableName(), false);
                builder.append("LIMIT 1");
                cassandra_client.set_cql_version(CassandraConstants.CQL_VERSION_3_0);
                CqlResult cqlResult = cassandra_client.execute_cql3_query(ByteBufferUtil.bytes(builder.toString()),
                        Compression.NONE, ConsistencyLevel.ONE);

                KunderaCoreUtils.printQuery(builder.toString(), showQuery);
                CqlMetadata originalMetadata = cqlResult.getSchema();

                int compareResult = originalMetadata.compareTo(metadata);
                if (compareResult > 0)
                {
                    onLog(tableInfo, metadata, value_types, originalMetadata);
                    throw new SchemaGenerationException(
                            "Schema mismatch!, validation failed. see above table for mismatch");
                }
            }
            else
            {
                onValidateTable(ksDef, tableInfo);
            }
        }
    }
599805
@Override
  public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
    if (pvalue == null) {
      return true;
    }
    try {
      String countryCode =
          BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, fieldCountryCode);
      final String postalCode =
          BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, fieldPostalCode);
      if (StringUtils.isEmpty(postalCode)) {
        return true;
      }

      if (allowLowerCaseCountryCode) {
        countryCode = StringUtils.upperCase(countryCode);
      }

      final String regExCheck = POSTAL_CODE_MAP.postalCodes().get(countryCode);
      if (regExCheck == null) {
        return true;
      }
      if (postalCode.matches(regExCheck)) {
        return true;
      }
      switchContext(pcontext);
      return false;
    } catch (final Exception ignore) {
      switchContext(pcontext);
      return false;
    }
  }
740651
@Override
    protected void validate(List<TableInfo> tableInfos)
    {
        List listTables = r.db(databaseName).tableList().run(connection);

        for (TableInfo tableInfo : tableInfos)
        {
            try
            {
                if (!listTables.contains(tableInfo.getTableName()))
                {
                    throw new SchemaGenerationException("Table: " + tableInfo.getTableName() + " does not exist ");
                }
            }
            catch (Exception e)
            {
                logger.error("Error while validating tables, Caused by: " + e.getMessage());
                throw new KunderaException("Error while validating tables, Caused by: " + e.getMessage());
            }
        }
    }
1188438
public function convertException($message, DriverException $exception)
    {
        if (strpos($exception->getMessage(), 'database is locked') !== false) {
            return new Exception\LockWaitTimeoutException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'must be unique') !== false ||
            strpos($exception->getMessage(), 'is not unique') !== false ||
            strpos($exception->getMessage(), 'are not unique') !== false ||
            strpos($exception->getMessage(), 'UNIQUE constraint failed') !== false
        ) {
            return new Exception\UniqueConstraintViolationException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'may not be NULL') !== false ||
            strpos($exception->getMessage(), 'NOT NULL constraint failed') !== false
        ) {
            return new Exception\NotNullConstraintViolationException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'no such table:') !== false) {
            return new Exception\TableNotFoundException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'already exists') !== false) {
            return new Exception\TableExistsException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'has no column named') !== false) {
            return new Exception\InvalidFieldNameException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'ambiguous column name') !== false) {
            return new Exception\NonUniqueFieldNameException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'syntax error') !== false) {
            return new Exception\SyntaxErrorException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'attempt to write a readonly database') !== false) {
            return new Exception\ReadOnlyException($message, $exception);
        }

        if (strpos($exception->getMessage(), 'unable to open database file') !== false) {
            return new Exception\ConnectionException($message, $exception);
        }

        return new Exception\DriverException($message, $exception);
    }
693044
public SQLException exceptionWithQuery(ByteBuffer buffer, SQLException sqlEx,
      boolean explicitClosed) {
    if (options.dumpQueriesOnException || sqlEx.getErrorCode() == 1064 || explicitClosed) {
      return exceptionWithQuery(subQuery(buffer), sqlEx, explicitClosed);
    }
    return sqlEx;
  }
1189856
@Override
  public final Integer evalIntegerResult(
    final String pQuery, final String pColumnName) throws Exception {
    Integer result = null;
    IRecordSet<RS> recordSet = null;
    try {
      recordSet = retrieveRecords(pQuery);
      if (recordSet.moveToFirst()) {
        result = recordSet.getInteger(pColumnName);
      }
    } finally {
      if (recordSet != null) {
        recordSet.close();
      }
    }
    return result;
  }