text:
package org.postgresql.jdbc;

import static org.postgresql.util.internal.Nullness.castNonNull;

import org.postgresql.Driver;
import org.postgresql.PGNotification;
import org.postgresql.PGProperty;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.CachedQuery;
import org.postgresql.core.ConnectionFactory;
import org.postgresql.core.Encoding;
import org.postgresql.core.Oid;
import org.postgresql.core.Query;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.ReplicationProtocol;
import org.postgresql.core.ResultHandlerBase;
import org.postgresql.core.ServerVersion;
import org.postgresql.core.SqlCommand;
import org.postgresql.core.TransactionState;
import org.postgresql.core.TypeInfo;
import org.postgresql.core.Utils;
import org.postgresql.core.Version;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
import org.postgresql.replication.PGReplicationConnection;
import org.postgresql.replication.PGReplicationConnectionImpl;
import org.postgresql.util.GT;
import org.postgresql.util.HostSpec;
import org.postgresql.util.LruCache;
import org.postgresql.util.PGBinaryObject;
import org.postgresql.util.PGobject;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.xml.DefaultPGXmlFactoryFactory;
import org.postgresql.xml.LegacyInsecurePGXmlFactoryFactory;
import org.postgresql.xml.PGXmlFactoryFactory;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.PolyNull;
import org.checkerframework.dataflow.qual.Pure;

import java.io.IOException;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.ClientInfoStatus;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLPermission;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.sql.Types;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PgConnection implements BaseConnection {

  private static final Logger LOGGER = Logger.getLogger(PgConnection.class.getName());
  private static final Set<Integer> SUPPORTED_BINARY_OIDS = getSupportedBinaryOids();
  private static final SQLPermission SQL_PERMISSION_ABORT = new SQLPermission("callAbort");
  private static final SQLPermission SQL_PERMISSION_NETWORK_TIMEOUT = new SQLPermission("setNetworkTimeout");

  private enum ReadOnlyBehavior {
    ignore,
    transaction,
    always;
  }

  //
  // Data initialized on construction:
  //
  private final Properties clientInfo;

  /* URL we were created via */
  private final String creatingURL;

  private final ReadOnlyBehavior readOnlyBehavior;

  private @Nullable Throwable openStackTrace;

  /* Actual network handler */
  private final QueryExecutor queryExecutor;

  /* Query that runs COMMIT */
  private final Query commitQuery;
  /* Query that runs ROLLBACK */
  private final Query rollbackQuery;

  private final CachedQuery setSessionReadOnly;

  private final CachedQuery setSessionNotReadOnly;

  private final TypeInfo typeCache;

  private boolean disableColumnSanitiser = false;

  // Default statement prepare threshold.
  protected int prepareThreshold;

  /**
   * Default fetch size for statement.
   *
   * @see PGProperty#DEFAULT_ROW_FETCH_SIZE
   */
  protected int defaultFetchSize;

  // Default forcebinary option.
  protected boolean forcebinary = false;

  private int rsHoldability = ResultSet.CLOSE_CURSORS_AT_COMMIT;
  private int savepointId = 0;
  // Connection's autocommit state.
  private boolean autoCommit = true;
  // Connection's readonly state.
  private boolean readOnly = false;
  // Filter out database objects for which the current user has no privileges granted from the DatabaseMetaData
  private boolean  hideUnprivilegedObjects ;
  // Whether to include error details in logging and exceptions
  private final boolean logServerErrorDetail;
  // Bind String to UNSPECIFIED or VARCHAR?
  private final boolean bindStringAsVarchar;

  // Current warnings; there might be more on queryExecutor too.
  private @Nullable SQLWarning firstWarning;

  // Timer for scheduling TimerTasks for this connection.
  // Only instantiated if a task is actually scheduled.
  private volatile @Nullable Timer cancelTimer;

  private @Nullable PreparedStatement checkConnectionQuery;
  /**
   * Replication protocol in current version postgresql(10devel) supports a limited number of
   * commands.
   */
  private final boolean replicationConnection;

  private final LruCache<FieldMetadata.Key, FieldMetadata> fieldMetadataCache;

  private final @Nullable String xmlFactoryFactoryClass;
  private @Nullable PGXmlFactoryFactory xmlFactoryFactory;

  final CachedQuery borrowQuery(String sql) throws SQLException {
    return queryExecutor.borrowQuery(sql);
  }

  final CachedQuery borrowCallableQuery(String sql) throws SQLException {
    return queryExecutor.borrowCallableQuery(sql);
  }

  private CachedQuery borrowReturningQuery(String sql, String @Nullable [] columnNames)
      throws SQLException {
    return queryExecutor.borrowReturningQuery(sql, columnNames);
  }

  @Override
  public CachedQuery createQuery(String sql, boolean escapeProcessing, boolean isParameterized,
      String... columnNames)
      throws SQLException {
    return queryExecutor.createQuery(sql, escapeProcessing, isParameterized, columnNames);
  }

  void releaseQuery(CachedQuery cachedQuery) {
    queryExecutor.releaseQuery(cachedQuery);
  }

  @Override
  public void setFlushCacheOnDeallocate(boolean flushCacheOnDeallocate) {
    queryExecutor.setFlushCacheOnDeallocate(flushCacheOnDeallocate);
    LOGGER.log(Level.FINE, "  setFlushCacheOnDeallocate = {0}", flushCacheOnDeallocate);
  }

  //
  // Ctor.
  //
  @SuppressWarnings({"method.invocation.invalid", "argument.type.incompatible"})
  public PgConnection(HostSpec[] hostSpecs,
                      String user,
                      String database,
                      Properties info,
                      String url) throws SQLException {
    // Print out the driver version number
    LOGGER.log(Level.FINE, org.postgresql.util.DriverInfo.DRIVER_FULL_NAME);

    this.creatingURL = url;

    this.readOnlyBehavior = getReadOnlyBehavior(PGProperty.READ_ONLY_MODE.get(info));

    setDefaultFetchSize(PGProperty.DEFAULT_ROW_FETCH_SIZE.getInt(info));

    setPrepareThreshold(PGProperty.PREPARE_THRESHOLD.getInt(info));
    if (prepareThreshold == -1) {
      setForceBinary(true);
    }

    // Now make the initial connection and set up local state
    this.queryExecutor = ConnectionFactory.openConnection(hostSpecs, user, database, info);

    // WARNING for unsupported servers (8.1 and lower are not supported)
    if (LOGGER.isLoggable(Level.WARNING) && !haveMinimumServerVersion(ServerVersion.v8_2)) {
      LOGGER.log(Level.WARNING, "Unsupported Server Version: {0}", queryExecutor.getServerVersion());
    }

    setSessionReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY", false, true);
    setSessionNotReadOnly = createQuery("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE", false, true);

    // Set read-only early if requested
    if (PGProperty.READ_ONLY.getBoolean(info)) {
      setReadOnly(true);
    }

    this.hideUnprivilegedObjects = PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(info);

    Set<Integer> binaryOids = getBinaryOids(info);

    // split for receive and send for better control
    Set<Integer> useBinarySendForOids = new HashSet<Integer>(binaryOids);

    Set<Integer> useBinaryReceiveForOids = new HashSet<Integer>(binaryOids);

    /*
     * Does not pass unit tests because unit tests expect setDate to have millisecond accuracy
     * whereas the binary transfer only supports date accuracy.
     */
    useBinarySendForOids.remove(Oid.DATE);

    queryExecutor.setBinaryReceiveOids(useBinaryReceiveForOids);
    queryExecutor.setBinarySendOids(useBinarySendForOids);

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.log(Level.FINEST, "    types using binary send = {0}", oidsToString(useBinarySendForOids));
      LOGGER.log(Level.FINEST, "    types using binary receive = {0}", oidsToString(useBinaryReceiveForOids));
      LOGGER.log(Level.FINEST, "    integer date/time = {0}", queryExecutor.getIntegerDateTimes());
    }

    //
    // String -> text or unknown?
    //

    String stringType = PGProperty.STRING_TYPE.get(info);
    if (stringType != null) {
      if (stringType.equalsIgnoreCase("unspecified")) {
        bindStringAsVarchar = false;
      } else if (stringType.equalsIgnoreCase("varchar")) {
        bindStringAsVarchar = true;
      } else {
        throw new PSQLException(
            GT.tr("Unsupported value for stringtype parameter: {0}", stringType),
            PSQLState.INVALID_PARAMETER_VALUE);
      }
    } else {
      bindStringAsVarchar = true;
    }

    // Initialize timestamp stuff
    timestampUtils = new TimestampUtils(!queryExecutor.getIntegerDateTimes(),
        new QueryExecutorTimeZoneProvider(queryExecutor));

    // Initialize common queries.
    // isParameterized==true so full parse is performed and the engine knows the query
    // is not a compound query with ; inside, so it could use parse/bind/exec messages
    commitQuery = createQuery("COMMIT", false, true).query;
    rollbackQuery = createQuery("ROLLBACK", false, true).query;

    int unknownLength = PGProperty.UNKNOWN_LENGTH.getInt(info);

    // Initialize object handling
    typeCache = createTypeInfo(this, unknownLength);
    initObjectTypes(info);

    if (PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(info)) {
      openStackTrace = new Throwable("Connection was created at this point:");
    }
    this.logServerErrorDetail = PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info);
    this.disableColumnSanitiser = PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(info);

    if (haveMinimumServerVersion(ServerVersion.v8_3)) {
      typeCache.addCoreType("uuid", Oid.UUID, Types.OTHER, "java.util.UUID", Oid.UUID_ARRAY);
      typeCache.addCoreType("xml", Oid.XML, Types.SQLXML, "java.sql.SQLXML", Oid.XML_ARRAY);
    }

    this.clientInfo = new Properties();
    if (haveMinimumServerVersion(ServerVersion.v9_0)) {
      String appName = PGProperty.APPLICATION_NAME.get(info);
      if (appName == null) {
        appName = "";
      }
      this.clientInfo.put("ApplicationName", appName);
    }

    fieldMetadataCache = new LruCache<FieldMetadata.Key, FieldMetadata>(
            Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS.getInt(info)),
            Math.max(0, PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getInt(info) * 1024L * 1024L),
        false);

    replicationConnection = PGProperty.REPLICATION.get(info) != null;

    xmlFactoryFactoryClass = PGProperty.XML_FACTORY_FACTORY.get(info);
  }

  private static ReadOnlyBehavior getReadOnlyBehavior(String property) {
    try {
      return ReadOnlyBehavior.valueOf(property);
    } catch (IllegalArgumentException e) {
      try {
        return ReadOnlyBehavior.valueOf(property.toLowerCase(Locale.US));
      } catch (IllegalArgumentException e2) {
        return ReadOnlyBehavior.transaction;
      }
    }
  }

  private static Set<Integer> getSupportedBinaryOids() {
    return new HashSet<Integer>(Arrays.asList(
        Oid.BYTEA,
        Oid.INT2,
        Oid.INT4,
        Oid.INT8,
        Oid.FLOAT4,
        Oid.FLOAT8,
        Oid.NUMERIC,
        Oid.TIME,
        Oid.DATE,
        Oid.TIMETZ,
        Oid.TIMESTAMP,
        Oid.TIMESTAMPTZ,
        Oid.BYTEA_ARRAY,
        Oid.INT2_ARRAY,
        Oid.INT4_ARRAY,
        Oid.INT8_ARRAY,
        Oid.OID_ARRAY,
        Oid.FLOAT4_ARRAY,
        Oid.FLOAT8_ARRAY,
        Oid.VARCHAR_ARRAY,
        Oid.TEXT_ARRAY,
        Oid.POINT,
        Oid.BOX,
        Oid.UUID));
  }

  private static Set<Integer> getBinaryOids(Properties info) throws PSQLException {
    boolean binaryTransfer = PGProperty.BINARY_TRANSFER.getBoolean(info);
    // Formats that currently have binary protocol support
    Set<Integer> binaryOids = new HashSet<Integer>(32);
    if (binaryTransfer) {
      binaryOids.addAll(SUPPORTED_BINARY_OIDS);
    }

    String oids = PGProperty.BINARY_TRANSFER_ENABLE.get(info);
    if (oids != null) {
      binaryOids.addAll(getOidSet(oids));
    }
    oids = PGProperty.BINARY_TRANSFER_DISABLE.get(info);
    if (oids != null) {
      binaryOids.removeAll(getOidSet(oids));
    }

    return binaryOids;
  }

  private static Set<Integer> getOidSet(String oidList) throws PSQLException {
    Set<Integer> oids = new HashSet<Integer>();
    StringTokenizer tokenizer = new StringTokenizer(oidList, ",");
    while (tokenizer.hasMoreTokens()) {
      String oid = tokenizer.nextToken();
      oids.add(Oid.valueOf(oid));
    }
    return oids;
  }

  private String oidsToString(Set<Integer> oids) {
    StringBuilder sb = new StringBuilder();
    for (Integer oid : oids) {
      sb.append(Oid.toString(oid));
      sb.append(',');
    }
    if (sb.length() > 0) {
      sb.setLength(sb.length() - 1);
    } else {
      sb.append(" <none>");
    }
    return sb.toString();
  }

  private final TimestampUtils timestampUtils;

  public TimestampUtils getTimestampUtils() {
    return timestampUtils;
  }

  /**
   * The current type mappings.
   */
  protected Map<String, Class<?>> typemap = new HashMap<String, Class<?>>();

  @Override
  public Statement createStatement() throws SQLException {
    // We now follow the spec and default to TYPE_FORWARD_ONLY.
    return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  }

  @Override
  public PreparedStatement prepareStatement(String sql) throws SQLException {
    return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  }

  @Override
  public CallableStatement prepareCall(String sql) throws SQLException {
    return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  }

  @Override
  public Map<String, Class<?>> getTypeMap() throws SQLException {
    checkClosed();
    return typemap;
  }

  public QueryExecutor getQueryExecutor() {
    return queryExecutor;
  }

  public ReplicationProtocol getReplicationProtocol() {
    return queryExecutor.getReplicationProtocol();
  }

  /**
   * This adds a warning to the warning chain.
   *
   * @param warn warning to add
   */
  public void addWarning(SQLWarning warn) {
    // Add the warning to the chain
    if (firstWarning != null) {
      firstWarning.setNextWarning(warn);
    } else {
      firstWarning = warn;
    }

  }

  @Override
  public ResultSet execSQLQuery(String s) throws SQLException {
    return execSQLQuery(s, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  }

  @Override
  public ResultSet execSQLQuery(String s, int resultSetType, int resultSetConcurrency)
      throws SQLException {
    BaseStatement stat = (BaseStatement) createStatement(resultSetType, resultSetConcurrency);
    boolean hasResultSet = stat.executeWithFlags(s, QueryExecutor.QUERY_SUPPRESS_BEGIN);

    while (!hasResultSet && stat.getUpdateCount() != -1) {
      hasResultSet = stat.getMoreResults();
    }

    if (!hasResultSet) {
      throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
    }

    // Transfer warnings to the connection, since the user never
    // has a chance to see the statement itself.
    SQLWarning warnings = stat.getWarnings();
    if (warnings != null) {
      addWarning(warnings);
    }

    return castNonNull(stat.getResultSet(), "hasResultSet==true, yet getResultSet()==null");
  }

  @Override
  public void execSQLUpdate(String s) throws SQLException {
    BaseStatement stmt = (BaseStatement) createStatement();
    if (stmt.executeWithFlags(s, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS
        | QueryExecutor.QUERY_SUPPRESS_BEGIN)) {
      throw new PSQLException(GT.tr("A result was returned when none was expected."),
          PSQLState.TOO_MANY_RESULTS);
    }

    // Transfer warnings to the connection, since the user never
    // has a chance to see the statement itself.
    SQLWarning warnings = stmt.getWarnings();
    if (warnings != null) {
      addWarning(warnings);
    }

    stmt.close();
  }

  void execSQLUpdate(CachedQuery query) throws SQLException {
    BaseStatement stmt = (BaseStatement) createStatement();
    if (stmt.executeWithFlags(query, QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS
        | QueryExecutor.QUERY_SUPPRESS_BEGIN)) {
      throw new PSQLException(GT.tr("A result was returned when none was expected."),
          PSQLState.TOO_MANY_RESULTS);
    }

    // Transfer warnings to the connection, since the user never
    // has a chance to see the statement itself.
    SQLWarning warnings = stmt.getWarnings();
    if (warnings != null) {
      addWarning(warnings);
    }

    stmt.close();
  }

  /**
   *
In SQL, a result table can be retrieved through a cursor that is named. The current row of a
   * result can be updated or deleted using a positioned update/delete statement that references the
   * cursor name.

   *
   *
We do not support positioned update/delete, so this is a no-op.

   *
   * @param cursor the cursor name
   * @throws SQLException if a database access error occurs
   */
  public void setCursorName(String cursor) throws SQLException {
    checkClosed();
    // No-op.
  }

  /**
   * getCursorName gets the cursor name.
   *
   * @return the current cursor name
   * @throws SQLException if a database access error occurs
   */
  public @Nullable String getCursorName() throws SQLException {
    checkClosed();
    return null;
  }

  /**
   *
We are required to bring back certain information by the DatabaseMetaData class. These
   * functions do that.

   *
   *
Method getURL() brings back the URL (good job we saved it)

   *
   * @return the url
   * @throws SQLException just in case...
   */
  public String getURL() throws SQLException {
    return creatingURL;
  }

  /**
   * Method getUserName() brings back the User Name (again, we saved it).
   *
   * @return the user name
   * @throws SQLException just in case...
   */
  public String getUserName() throws SQLException {
    return queryExecutor.getUser();
  }

  public Fastpath getFastpathAPI() throws SQLException {
    checkClosed();
    if (fastpath == null) {
      fastpath = new Fastpath(this);
    }
    return fastpath;
  }

  // This holds a reference to the Fastpath API if already open
  private @Nullable Fastpath fastpath;

  public LargeObjectManager getLargeObjectAPI() throws SQLException {
    checkClosed();
    if (largeobject == null) {
      largeobject = new LargeObjectManager(this);
    }
    return largeobject;
  }

  // This holds a reference to the LargeObject API if already open
  private @Nullable LargeObjectManager largeobject;

  /*
   * This method is used internally to return an object based around org.postgresql's more unique
   * data types.
   *
   *
It uses an internal HashMap to get the handling class. If the type is not supported, then an
   * instance of org.postgresql.util.PGobject is returned.
   *
   * You can use the getValue() or setValue() methods to handle the returned object. Custom objects
   * can have their own methods.
   *
   * @return PGobject for this type, and set to value
   *
   * @exception SQLException if value is not correct for this type
   */
  @Override
  public Object getObject(String type, @Nullable String value, byte @Nullable [] byteValue)
      throws SQLException {
    if (typemap != null) {
      Class<?> c = typemap.get(type);
      if (c != null) {
        // Handle the type (requires SQLInput & SQLOutput classes to be implemented)
        throw new PSQLException(GT.tr("Custom type maps are not supported."),
            PSQLState.NOT_IMPLEMENTED);
      }
    }

    PGobject obj = null;

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.log(Level.FINEST, "Constructing object from type={0} value=<{1}>", new Object[]{type, value});
    }

    try {
      Class<? extends PGobject> klass = typeCache.getPGobject(type);

      // If className is not null, then try to instantiate it,
      // It must be basetype PGobject

      // This is used to implement the org.postgresql unique types (like lseg,
      // point, etc).

      if (klass != null) {
        obj = klass.newInstance();
        obj.setType(type);
        if (byteValue != null && obj instanceof PGBinaryObject) {
          PGBinaryObject binObj = (PGBinaryObject) obj;
          binObj.setByteValue(byteValue, 0);
        } else {
          obj.setValue(castNonNull(value));
        }
      } else {
        // If className is null, then the type is unknown.
        // so return a PGobject with the type set, and the value set
        obj = new PGobject();
        obj.setType(type);
        obj.setValue(castNonNull(value));
      }

      return obj;
    } catch (SQLException sx) {
      // rethrow the exception. Done because we capture any others next
      throw sx;
    } catch (Exception ex) {
      throw new PSQLException(GT.tr("Failed to create object for: {0}.", type),
          PSQLState.CONNECTION_FAILURE, ex);
    }
  }

  protected TypeInfo createTypeInfo(BaseConnection conn, int unknownLength) {
    return new TypeInfoCache(conn, unknownLength);
  }

  public TypeInfo getTypeInfo() {
    return typeCache;
  }

  @Override
  public void addDataType(String type, String name) {
    try {
      addDataType(type, Class.forName(name).asSubclass(PGobject.class));
    } catch (Exception e) {
      throw new RuntimeException("Cannot register new type: " + e);
    }
  }

  @Override
  public void addDataType(String type, Class<? extends PGobject> klass) throws SQLException {
    checkClosed();
    typeCache.addDataType(type, klass);
  }

  // This initialises the objectTypes hash map
  private void initObjectTypes(Properties info) throws SQLException {
    // Add in the types that come packaged with the driver.
    // These can be overridden later if desired.
    addDataType("box", org.postgresql.geometric.PGbox.class);
    addDataType("circle", org.postgresql.geometric.PGcircle.class);
    addDataType("line", org.postgresql.geometric.PGline.class);
    addDataType("lseg", org.postgresql.geometric.PGlseg.class);
    addDataType("path", org.postgresql.geometric.PGpath.class);
    addDataType("point", org.postgresql.geometric.PGpoint.class);
    addDataType("polygon", org.postgresql.geometric.PGpolygon.class);
    addDataType("money", org.postgresql.util.PGmoney.class);
    addDataType("interval", org.postgresql.util.PGInterval.class);

    Enumeration<?> e = info.propertyNames();
    while (e.hasMoreElements()) {
      String propertyName = (String) e.nextElement();
      if (propertyName != null && propertyName.startsWith("datatype.")) {
        String typeName = propertyName.substring(9);
        String className = castNonNull(info.getProperty(propertyName));
        Class<?> klass;

        try {
          klass = Class.forName(className);
        } catch (ClassNotFoundException cnfe) {
          throw new PSQLException(
              GT.tr("Unable to load the class {0} responsible for the datatype {1}",
                  className, typeName),
              PSQLState.SYSTEM_ERROR, cnfe);
        }

        addDataType(typeName, klass.asSubclass(PGobject.class));
      }
    }
  }

  /**
   * Note: even though {@code Statement} is automatically closed when it is garbage
   * collected, it is better to close it explicitly to lower resource consumption.
   *
   * {@inheritDoc}
   */
  @Override
  public void close() throws SQLException {
    if (queryExecutor == null) {
      // This might happen in case constructor throws an exception (e.g. host being not available).
      // When that happens the connection is still registered in the finalizer queue, so it gets finalized
      return;
    }
    releaseTimer();
    queryExecutor.close();
    openStackTrace = null;
  }

  @Override
  public String nativeSQL(String sql) throws SQLException {
    checkClosed();
    CachedQuery cachedQuery = queryExecutor.createQuery(sql, false, true);

    return cachedQuery.query.getNativeSql();
  }

  @Override
  public synchronized @Nullable SQLWarning getWarnings() throws SQLException {
    checkClosed();
    SQLWarning newWarnings = queryExecutor.getWarnings(); // NB: also clears them.
    if (firstWarning == null) {
      firstWarning = newWarnings;
    } else if (newWarnings != null) {
      firstWarning.setNextWarning(newWarnings); // Chain them on.
    }

    return firstWarning;
  }

  @Override
  public synchronized void clearWarnings() throws SQLException {
    checkClosed();
    //noinspection ThrowableNotThrown
    queryExecutor.getWarnings(); // Clear and discard.
    firstWarning = null;
  }

  @Override
  public void setReadOnly(boolean readOnly) throws SQLException {
    checkClosed();
    if (queryExecutor.getTransactionState() != TransactionState.IDLE) {
      throw new PSQLException(
          GT.tr("Cannot change transaction read-only property in the middle of a transaction."),
          PSQLState.ACTIVE_SQL_TRANSACTION);
    }

    if (readOnly != this.readOnly && autoCommit && this.readOnlyBehavior == ReadOnlyBehavior.always) {
      execSQLUpdate(readOnly ? setSessionReadOnly : setSessionNotReadOnly);
    }

    this.readOnly = readOnly;
    LOGGER.log(Level.FINE, "  setReadOnly = {0}", readOnly);
  }

  @Override
  public boolean isReadOnly() throws SQLException {
    checkClosed();
    return readOnly;
  }

  @Override
  public boolean hintReadOnly() {
    return readOnly && readOnlyBehavior != ReadOnlyBehavior.ignore;
  }

  @Override
  public void setAutoCommit(boolean autoCommit) throws SQLException {
    checkClosed();

    if (this.autoCommit == autoCommit) {
      return;
    }

    if (!this.autoCommit) {
      commit();
    }

    // if the connection is read only, we need to make sure session settings are
    // correct when autocommit status changed
    if (this.readOnly && readOnlyBehavior == ReadOnlyBehavior.always) {
      // if we are turning on autocommit, we need to set session
      // to read only
      if (autoCommit) {
        this.autoCommit = true;
        execSQLUpdate(setSessionReadOnly);
      } else {
        // if we are turning auto commit off, we need to
        // disable session
        execSQLUpdate(setSessionNotReadOnly);
      }
    }

    this.autoCommit = autoCommit;
    LOGGER.log(Level.FINE, "  setAutoCommit = {0}", autoCommit);
  }

  @Override
  public boolean getAutoCommit() throws SQLException {
    checkClosed();
    return this.autoCommit;
  }

  private void executeTransactionCommand(Query query) throws SQLException {
    int flags = QueryExecutor.QUERY_NO_METADATA | QueryExecutor.QUERY_NO_RESULTS
        | QueryExecutor.QUERY_SUPPRESS_BEGIN;
    if (prepareThreshold == 0) {
      flags |= QueryExecutor.QUERY_ONESHOT;
    }

    try {
      getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags);
    } catch (SQLException e) {
      // Don't retry composite queries as it might get partially executed
      if (query.getSubqueries() != null || !queryExecutor.willHealOnRetry(e)) {
        throw e;
      }
      query.close();
      // retry
      getQueryExecutor().execute(query, null, new TransactionCommandHandler(), 0, 0, flags);
    }
  }

  @Override
  public void commit() throws SQLException {
    checkClosed();

    if (autoCommit) {
      throw new PSQLException(GT.tr("Cannot commit when autoCommit is enabled."),
          PSQLState.NO_ACTIVE_SQL_TRANSACTION);
    }

    if (queryExecutor.getTransactionState() != TransactionState.IDLE) {
      executeTransactionCommand(commitQuery);
    }
  }

  protected void checkClosed() throws SQLException {
    if (isClosed()) {
      throw new PSQLException(GT.tr("This connection has been closed."),
          PSQLState.CONNECTION_DOES_NOT_EXIST);
    }
  }

  @Override
  public void rollback() throws SQLException {
    checkClosed();

    if (autoCommit) {
      throw new PSQLException(GT.tr("Cannot rollback when autoCommit is enabled."),
          PSQLState.NO_ACTIVE_SQL_TRANSACTION);
    }

    if (queryExecutor.getTransactionState() != TransactionState.IDLE) {
      executeTransactionCommand(rollbackQuery);
    } else {
      // just log for debugging
      LOGGER.log(Level.FINE, "Rollback requested but no transaction in progress");
    }
  }

  public TransactionState getTransactionState() {
    return queryExecutor.getTransactionState();
  }

  public int getTransactionIsolation() throws SQLException {
    checkClosed();

    String level = null;
    final ResultSet rs = execSQLQuery("SHOW TRANSACTION ISOLATION LEVEL"); // nb: no BEGIN triggered
    if (rs.next()) {
      level = rs.getString(1);
    }
    rs.close();

    // TODO revisit: throw exception instead of silently eating the error in unknown cases?
    if (level == null) {
      return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
    }

    level = level.toUpperCase(Locale.US);
    if (level.equals("READ COMMITTED")) {
      return Connection.TRANSACTION_READ_COMMITTED;
    }
    if (level.equals("READ UNCOMMITTED")) {
      return Connection.TRANSACTION_READ_UNCOMMITTED;
    }
    if (level.equals("REPEATABLE READ")) {
      return Connection.TRANSACTION_REPEATABLE_READ;
    }
    if (level.equals("SERIALIZABLE")) {
      return Connection.TRANSACTION_SERIALIZABLE;
    }

    return Connection.TRANSACTION_READ_COMMITTED; // Best guess.
  }

  public void setTransactionIsolation(int level) throws SQLException {
    checkClosed();

    if (queryExecutor.getTransactionState() != TransactionState.IDLE) {
      throw new PSQLException(
          GT.tr("Cannot change transaction isolation level in the middle of a transaction."),
          PSQLState.ACTIVE_SQL_TRANSACTION);
    }

    String isolationLevelName = getIsolationLevelName(level);
    if (isolationLevelName == null) {
      throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level),
          PSQLState.NOT_IMPLEMENTED);
    }

    String isolationLevelSQL =
        "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName;
    execSQLUpdate(isolationLevelSQL); // nb: no BEGIN triggered
    LOGGER.log(Level.FINE, "  setTransactionIsolation = {0}", isolationLevelName);
  }

  protected @Nullable String getIsolationLevelName(int level) {
    switch (level) {
      case Connection.TRANSACTION_READ_COMMITTED:
        return "READ COMMITTED";
      case Connection.TRANSACTION_SERIALIZABLE:
        return "SERIALIZABLE";
      case Connection.TRANSACTION_READ_UNCOMMITTED:
        return "READ UNCOMMITTED";
      case Connection.TRANSACTION_REPEATABLE_READ:
        return "REPEATABLE READ";
      default:
        return null;
    }
  }

  public void setCatalog(String catalog) throws SQLException {
    checkClosed();
    // no-op
  }

  public String getCatalog() throws SQLException {
    checkClosed();
    return queryExecutor.getDatabase();
  }

  public boolean getHideUnprivilegedObjects() {
    return hideUnprivilegedObjects;
  }

  /**
   *
Overrides finalize(). If called, it closes the connection.

   *
   *
This was done at the request of Rachel
   * Greenham who hit a problem where multiple clients didn't close the connection, and once a
   * fortnight enough clients were open to kill the postgres server.

   */
  protected void finalize() throws Throwable {
    try {
      if (openStackTrace != null) {
        LOGGER.log(Level.WARNING, GT.tr("Finalizing a Connection that was never closed:"), openStackTrace);
      }

      close();
    } finally {
      super.finalize();
    }
  }

  /**
   * Get server version number.
   *
   * @return server version number
   */
  public String getDBVersionNumber() {
    return queryExecutor.getServerVersion();
  }

  /**
   * Get server major version.
   *
   * @return server major version
   */
  public int getServerMajorVersion() {
    try {
      StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd
      return integerPart(versionTokens.nextToken()); // return X
    } catch (NoSuchElementException e) {
      return 0;
    }
  }

  /**
   * Get server minor version.
   *
   * @return server minor version
   */
  public int getServerMinorVersion() {
    try {
      StringTokenizer versionTokens = new StringTokenizer(queryExecutor.getServerVersion(), "."); // aaXbb.ccYdd
      versionTokens.nextToken(); // Skip aaXbb
      return integerPart(versionTokens.nextToken()); // return Y
    } catch (NoSuchElementException e) {
      return 0;
    }
  }

  @Override
  public boolean haveMinimumServerVersion(int ver) {
    return queryExecutor.getServerVersionNum() >= ver;
  }

  @Override
  public boolean haveMinimumServerVersion(Version ver) {
    return haveMinimumServerVersion(ver.getVersionNum());
  }

  @Pure
  @Override
  public Encoding getEncoding() {
    return queryExecutor.getEncoding();
  }

  @Override
  public byte @PolyNull [] encodeString(@PolyNull String str) throws SQLException {
    try {
      return getEncoding().encode(str);
    } catch (IOException ioe) {
      throw new PSQLException(GT.tr("Unable to translate data into the desired encoding."),
          PSQLState.DATA_ERROR, ioe);
    }
  }

  @Override
  public String escapeString(String str) throws SQLException {
    return Utils.escapeLiteral(null, str, queryExecutor.getStandardConformingStrings())
        .toString();
  }

  @Override
  public boolean getStandardConformingStrings() {
    return queryExecutor.getStandardConformingStrings();
  }

  // This is a cache of the DatabaseMetaData instance for this connection
  protected java.sql.@Nullable DatabaseMetaData metadata;

  @Override
  public boolean isClosed() throws SQLException {
    return queryExecutor.isClosed();
  }

  @Override
  public void cancelQuery() throws SQLException {
    checkClosed();
    queryExecutor.sendQueryCancel();
  }

  @Override
  public PGNotification[] getNotifications() throws SQLException {
    return getNotifications(-1);
  }

  @Override
  public PGNotification[] getNotifications(int timeoutMillis) throws SQLException {
    checkClosed();
    getQueryExecutor().processNotifies(timeoutMillis);
    // Backwards-compatibility hand-holding.
    PGNotification[] notifications = queryExecutor.getNotifications();
    return notifications;
  }

  /**
   * Handler for transaction queries.
   */
  private class TransactionCommandHandler extends ResultHandlerBase {
    public void handleCompletion() throws SQLException {
      SQLWarning warning = getWarning();
      if (warning != null) {
        PgConnection.this.addWarning(warning);
      }
      super.handleCompletion();
    }
  }

  public int getPrepareThreshold() {
    return prepareThreshold;
  }

  public void setDefaultFetchSize(int fetchSize) throws SQLException {
    if (fetchSize < 0) {
      throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."),
          PSQLState.INVALID_PARAMETER_VALUE);
    }

    this.defaultFetchSize = fetchSize;
    LOGGER.log(Level.FINE, "  setDefaultFetchSize = {0}", fetchSize);
  }

  public int getDefaultFetchSize() {
    return defaultFetchSize;
  }

  public void setPrepareThreshold(int newThreshold) {
    this.prepareThreshold = newThreshold;
    LOGGER.log(Level.FINE, "  setPrepareThreshold = {0}", newThreshold);
  }

  public boolean getForceBinary() {
    return forcebinary;
  }

  public void setForceBinary(boolean newValue) {
    this.forcebinary = newValue;
    LOGGER.log(Level.FINE, "  setForceBinary = {0}", newValue);
  }

  public void setTypeMapImpl(Map<String, Class<?>> map) throws SQLException {
    typemap = map;
  }

  public Logger getLogger() {
    return LOGGER;
  }

  public int getProtocolVersion() {
    return queryExecutor.getProtocolVersion();
  }

  public boolean getStringVarcharFlag() {
    return bindStringAsVarchar;
  }

  private @Nullable CopyManager copyManager;

  public CopyManager getCopyAPI() throws SQLException {
    checkClosed();
    if (copyManager == null) {
      copyManager = new CopyManager(this);
    }
    return copyManager;
  }

  public boolean binaryTransferSend(int oid) {
    return queryExecutor.useBinaryForSend(oid);
  }

  public int getBackendPID() {
    return queryExecutor.getBackendPID();
  }

  public boolean isColumnSanitiserDisabled() {
    return this.disableColumnSanitiser;
  }

  public void setDisableColumnSanitiser(boolean disableColumnSanitiser) {
    this.disableColumnSanitiser = disableColumnSanitiser;
    LOGGER.log(Level.FINE, "  setDisableColumnSanitiser = {0}", disableColumnSanitiser);
  }

  @Override
  public PreferQueryMode getPreferQueryMode() {
    return queryExecutor.getPreferQueryMode();
  }

  @Override
  public AutoSave getAutosave() {
    return queryExecutor.getAutoSave();
  }

  @Override
  public void setAutosave(AutoSave autoSave) {
    queryExecutor.setAutoSave(autoSave);
    LOGGER.log(Level.FINE, "  setAutosave = {0}", autoSave.value());
  }

  protected void abort() {
    queryExecutor.abort();
  }

  private synchronized Timer getTimer() {
    if (cancelTimer == null) {
      cancelTimer = Driver.getSharedTimer().getTimer();
    }
    return cancelTimer;
  }

  private synchronized void releaseTimer() {
    if (cancelTimer != null) {
      cancelTimer = null;
      Driver.getSharedTimer().releaseTimer();
    }
  }

  @Override
  public void addTimerTask(TimerTask timerTask, long milliSeconds) {
    Timer timer = getTimer();
    timer.schedule(timerTask, milliSeconds);
  }

  @Override
  public void purgeTimerTasks() {
    Timer timer = cancelTimer;
    if (timer != null) {
      timer.purge();
    }
  }

  @Override
  public String escapeIdentifier(String identifier) throws SQLException {
    return Utils.escapeIdentifier(null, identifier).toString();
  }

  @Override
  public String escapeLiteral(String literal) throws SQLException {
    return Utils.escapeLiteral(null, literal, queryExecutor.getStandardConformingStrings())
        .toString();
  }

  @Override
  public LruCache<FieldMetadata.Key, FieldMetadata> getFieldMetadataCache() {
    return fieldMetadataCache;
  }

  @Override
  public PGReplicationConnection getReplicationAPI() {
    return new PGReplicationConnectionImpl(this);
  }

  // Parse a "dirty" integer surrounded by non-numeric characters
  private static int integerPart(String dirtyString) {
    int start = 0;

    while (start < dirtyString.length() && !Character.isDigit(dirtyString.charAt(start))) {
      ++start;
    }

    int end = start;
    while (end < dirtyString.length() && Character.isDigit(dirtyString.charAt(end))) {
      ++end;
    }

    if (start == end) {
      return 0;
    }

    return Integer.parseInt(dirtyString.substring(start, end));
  }

  @Override
  public Statement createStatement(int resultSetType, int resultSetConcurrency,
      int resultSetHoldability) throws SQLException {
    checkClosed();
    return new PgStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability);
  }

  @Override
  public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
      int resultSetHoldability) throws SQLException {
    checkClosed();
    return new PgPreparedStatement(this, sql, resultSetType, resultSetConcurrency,
        resultSetHoldability);
  }

  @Override
  public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
      int resultSetHoldability) throws SQLException {
    checkClosed();
    return new PgCallableStatement(this, sql, resultSetType, resultSetConcurrency,
        resultSetHoldability);
  }

  @Override
  public DatabaseMetaData getMetaData() throws SQLException {
    checkClosed();
    if (metadata == null) {
      metadata = new PgDatabaseMetaData(this);
    }
    return metadata;
  }

  @Override
  public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
    setTypeMapImpl(map);
    LOGGER.log(Level.FINE, "  setTypeMap = {0}", map);
  }

  protected Array makeArray(int oid, @Nullable String fieldString) throws SQLException {
    return new PgArray(this, oid, fieldString);
  }

  protected Blob makeBlob(long oid) throws SQLException {
    return new PgBlob(this, oid);
  }

  protected Clob makeClob(long oid) throws SQLException {
    return new PgClob(this, oid);
  }

  protected SQLXML makeSQLXML() throws SQLException {
    return new PgSQLXML(this);
  }

  @Override
  public Clob createClob() throws SQLException {
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "createClob()");
  }

  @Override
  public Blob createBlob() throws SQLException {
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "createBlob()");
  }

  @Override
  public NClob createNClob() throws SQLException {
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "createNClob()");
  }

  @Override
  public SQLXML createSQLXML() throws SQLException {
    checkClosed();
    return makeSQLXML();
  }

  @Override
  public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "createStruct(String, Object[])");
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @Override
  public Array createArrayOf(String typeName, @Nullable Object elements) throws SQLException {
    checkClosed();

    final TypeInfo typeInfo = getTypeInfo();

    final int oid = typeInfo.getPGArrayType(typeName);
    final char delim = typeInfo.getArrayDelimiter(oid);

    if (oid == Oid.UNSPECIFIED) {
      throw new PSQLException(GT.tr("Unable to find server array type for provided name {0}.", typeName),
          PSQLState.INVALID_NAME);
    }

    if (elements == null) {
      return makeArray(oid, null);
    }

    final ArrayEncoding.ArrayEncoder arraySupport = ArrayEncoding.getArrayEncoder(elements);
    if (arraySupport.supportBinaryRepresentation(oid) && getPreferQueryMode() != PreferQueryMode.SIMPLE) {
      return new PgArray(this, oid, arraySupport.toBinaryRepresentation(this, elements, oid));
    }

    final String arrayString = arraySupport.toArrayString(delim, elements);
    return makeArray(oid, arrayString);
  }

  @Override
  public Array createArrayOf(String typeName, @Nullable Object @Nullable [] elements)
      throws SQLException {
    return createArrayOf(typeName, (Object) elements);
  }

  @Override
  public boolean isValid(int timeout) throws SQLException {
    if (timeout < 0) {
      throw new PSQLException(GT.tr("Invalid timeout ({0}<0).", timeout),
          PSQLState.INVALID_PARAMETER_VALUE);
    }
    if (isClosed()) {
      return false;
    }
    boolean changedNetworkTimeout = false;
    try {
      int oldNetworkTimeout = getNetworkTimeout();
      int newNetworkTimeout = (int) Math.min(timeout * 1000L, Integer.MAX_VALUE);
      try {
        // change network timeout only if the new value is less than the current
        // (zero means infinite timeout)
        if (newNetworkTimeout != 0 && (oldNetworkTimeout == 0 || newNetworkTimeout < oldNetworkTimeout)) {
          changedNetworkTimeout = true;
          setNetworkTimeout(null, newNetworkTimeout);
        }
        if (replicationConnection) {
          Statement statement = createStatement();
          statement.execute("IDENTIFY_SYSTEM");
          statement.close();
        } else {
          if (checkConnectionQuery == null) {
            checkConnectionQuery = prepareStatement("");
          }
          checkConnectionQuery.executeUpdate();
        }
        return true;
      } finally {
        if (changedNetworkTimeout) {
          setNetworkTimeout(null, oldNetworkTimeout);
        }
      }
    } catch (SQLException e) {
      if (PSQLState.IN_FAILED_SQL_TRANSACTION.getState().equals(e.getSQLState())) {
        // "current transaction aborted", assume the connection is up and running
        return true;
      }
      LOGGER.log(Level.FINE, GT.tr("Validating connection."), e);
    }
    return false;
  }

  @Override
  public void setClientInfo(String name, @Nullable String value) throws SQLClientInfoException {
    try {
      checkClosed();
    } catch (final SQLException cause) {
      Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>();
      failures.put(name, ClientInfoStatus.REASON_UNKNOWN);
      throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause);
    }

    if (haveMinimumServerVersion(ServerVersion.v9_0) && "ApplicationName".equals(name)) {
      if (value == null) {
        value = "";
      }
      final String oldValue = queryExecutor.getApplicationName();
      if (value.equals(oldValue)) {
        return;
      }

      try {
        StringBuilder sql = new StringBuilder("SET application_name = '");
        Utils.escapeLiteral(sql, value, getStandardConformingStrings());
        sql.append("'");
        execSQLUpdate(sql.toString());
      } catch (SQLException sqle) {
        Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>();
        failures.put(name, ClientInfoStatus.REASON_UNKNOWN);
        throw new SQLClientInfoException(
            GT.tr("Failed to set ClientInfo property: {0}", "ApplicationName"), sqle.getSQLState(),
            failures, sqle);
      }
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "  setClientInfo = {0} {1}", new Object[]{name, value});
      }
      clientInfo.put(name, value);
      return;
    }

    addWarning(new SQLWarning(GT.tr("ClientInfo property not supported."),
        PSQLState.NOT_IMPLEMENTED.getState()));
  }

  @Override
  public void setClientInfo(Properties properties) throws SQLClientInfoException {
    try {
      checkClosed();
    } catch (final SQLException cause) {
      Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>();
      for (Map.Entry<Object, Object> e : properties.entrySet()) {
        failures.put((String) e.getKey(), ClientInfoStatus.REASON_UNKNOWN);
      }
      throw new SQLClientInfoException(GT.tr("This connection has been closed."), failures, cause);
    }

    Map<String, ClientInfoStatus> failures = new HashMap<String, ClientInfoStatus>();
    for (String name : new String[]{"ApplicationName"}) {
      try {
        setClientInfo(name, properties.getProperty(name, null));
      } catch (SQLClientInfoException e) {
        failures.putAll(e.getFailedProperties());
      }
    }

    if (!failures.isEmpty()) {
      throw new SQLClientInfoException(GT.tr("One or more ClientInfo failed."),
          PSQLState.NOT_IMPLEMENTED.getState(), failures);
    }
  }

  @Override
  public @Nullable String getClientInfo(String name) throws SQLException {
    checkClosed();
    clientInfo.put("ApplicationName", queryExecutor.getApplicationName());
    return clientInfo.getProperty(name);
  }

  @Override
  public Properties getClientInfo() throws SQLException {
    checkClosed();
    clientInfo.put("ApplicationName", queryExecutor.getApplicationName());
    return clientInfo;
  }

  public <T> T createQueryObject(Class<T> ifc) throws SQLException {
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "createQueryObject(Class<T>)");
  }

  public boolean getLogServerErrorDetail() {
    return logServerErrorDetail;
  }

  @Override
  public boolean isWrapperFor(Class<?> iface) throws SQLException {
    checkClosed();
    return iface.isAssignableFrom(getClass());
  }

  @Override
  public <T> T unwrap(Class<T> iface) throws SQLException {
    checkClosed();
    if (iface.isAssignableFrom(getClass())) {
      return iface.cast(this);
    }
    throw new SQLException("Cannot unwrap to " + iface.getName());
  }

  public @Nullable String getSchema() throws SQLException {
    checkClosed();
    Statement stmt = createStatement();
    try {
      ResultSet rs = stmt.executeQuery("select current_schema()");
      try {
        if (!rs.next()) {
          return null; // Is it ever possible?
        }
        return rs.getString(1);
      } finally {
        rs.close();
      }
    } finally {
      stmt.close();
    }
  }

  public void setSchema(@Nullable String schema) throws SQLException {
    checkClosed();
    Statement stmt = createStatement();
    try {
      if (schema == null) {
        stmt.executeUpdate("SET SESSION search_path TO DEFAULT");
      } else {
        StringBuilder sb = new StringBuilder();
        sb.append("SET SESSION search_path TO '");
        Utils.escapeLiteral(sb, schema, getStandardConformingStrings());
        sb.append("'");
        stmt.executeUpdate(sb.toString());
        LOGGER.log(Level.FINE, "  setSchema = {0}", schema);
      }
    } finally {
      stmt.close();
    }
  }

  public class AbortCommand implements Runnable {
    public void run() {
      abort();
    }
  }

  public void abort(Executor executor) throws SQLException {
    if (executor == null) {
      throw new SQLException("executor is null");
    }
    if (isClosed()) {
      return;
    }

    SQL_PERMISSION_ABORT.checkGuard(this);

    AbortCommand command = new AbortCommand();
    executor.execute(command);
  }

  public void setNetworkTimeout(@Nullable Executor executor /*not used*/, int milliseconds)
      throws SQLException {
    checkClosed();

    if (milliseconds < 0) {
      throw new PSQLException(GT.tr("Network timeout must be a value greater than or equal to 0."),
              PSQLState.INVALID_PARAMETER_VALUE);
    }

    SecurityManager securityManager = System.getSecurityManager();
    if (securityManager != null) {
      securityManager.checkPermission(SQL_PERMISSION_NETWORK_TIMEOUT);
    }

    try {
      queryExecutor.setNetworkTimeout(milliseconds);
    } catch (IOException ioe) {
      throw new PSQLException(GT.tr("Unable to set network timeout."),
              PSQLState.COMMUNICATION_ERROR, ioe);
    }
  }

  public int getNetworkTimeout() throws SQLException {
    checkClosed();

    try {
      return queryExecutor.getNetworkTimeout();
    } catch (IOException ioe) {
      throw new PSQLException(GT.tr("Unable to get network timeout."),
              PSQLState.COMMUNICATION_ERROR, ioe);
    }
  }

  @Override
  public void setHoldability(int holdability) throws SQLException {
    checkClosed();

    switch (holdability) {
      case ResultSet.CLOSE_CURSORS_AT_COMMIT:
        rsHoldability = holdability;
        break;
      case ResultSet.HOLD_CURSORS_OVER_COMMIT:
        rsHoldability = holdability;
        break;
      default:
        throw new PSQLException(GT.tr("Unknown ResultSet holdability setting: {0}.", holdability),
            PSQLState.INVALID_PARAMETER_VALUE);
    }
    LOGGER.log(Level.FINE, "  setHoldability = {0}", holdability);
  }

  @Override
  public int getHoldability() throws SQLException {
    checkClosed();
    return rsHoldability;
  }

  @Override
  public Savepoint setSavepoint() throws SQLException {
    checkClosed();

    String pgName;
    if (getAutoCommit()) {
      throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."),
          PSQLState.NO_ACTIVE_SQL_TRANSACTION);
    }

    PSQLSavepoint savepoint = new PSQLSavepoint(savepointId++);
    pgName = savepoint.getPGName();

    // Note we can't use execSQLUpdate because we don't want
    // to suppress BEGIN.
    Statement stmt = createStatement();
    stmt.executeUpdate("SAVEPOINT " + pgName);
    stmt.close();

    return savepoint;
  }

  @Override
  public Savepoint setSavepoint(String name) throws SQLException {
    checkClosed();

    if (getAutoCommit()) {
      throw new PSQLException(GT.tr("Cannot establish a savepoint in auto-commit mode."),
          PSQLState.NO_ACTIVE_SQL_TRANSACTION);
    }

    PSQLSavepoint savepoint = new PSQLSavepoint(name);

    // Note we can't use execSQLUpdate because we don't want
    // to suppress BEGIN.
    Statement stmt = createStatement();
    stmt.executeUpdate("SAVEPOINT " + savepoint.getPGName());
    stmt.close();

    return savepoint;
  }

  @Override
  public void rollback(Savepoint savepoint) throws SQLException {
    checkClosed();

    PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint;
    execSQLUpdate("ROLLBACK TO SAVEPOINT " + pgSavepoint.getPGName());
  }

  @Override
  public void releaseSavepoint(Savepoint savepoint) throws SQLException {
    checkClosed();

    PSQLSavepoint pgSavepoint = (PSQLSavepoint) savepoint;
    execSQLUpdate("RELEASE SAVEPOINT " + pgSavepoint.getPGName());
    pgSavepoint.invalidate();
  }

  @Override
  public Statement createStatement(int resultSetType, int resultSetConcurrency)
      throws SQLException {
    checkClosed();
    return createStatement(resultSetType, resultSetConcurrency, getHoldability());
  }

  @Override
  public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
      throws SQLException {
    checkClosed();
    return prepareStatement(sql, resultSetType, resultSetConcurrency, getHoldability());
  }

  @Override
  public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
      throws SQLException {
    checkClosed();
    return prepareCall(sql, resultSetType, resultSetConcurrency, getHoldability());
  }

  @Override
  public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
    if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) {
      return prepareStatement(sql);
    }

    return prepareStatement(sql, (String[]) null);
  }

  @Override
  public PreparedStatement prepareStatement(String sql, int @Nullable [] columnIndexes) throws SQLException {
    if (columnIndexes != null && columnIndexes.length == 0) {
      return prepareStatement(sql);
    }

    checkClosed();
    throw new PSQLException(GT.tr("Returning autogenerated keys is not supported."),
        PSQLState.NOT_IMPLEMENTED);
  }

  @Override
  public PreparedStatement prepareStatement(String sql, String @Nullable[] columnNames) throws SQLException {
    if (columnNames != null && columnNames.length == 0) {
      return prepareStatement(sql);
    }

    CachedQuery cachedQuery = borrowReturningQuery(sql, columnNames);
    PgPreparedStatement ps =
        new PgPreparedStatement(this, cachedQuery,
            ResultSet.TYPE_FORWARD_ONLY,
            ResultSet.CONCUR_READ_ONLY,
            getHoldability());
    Query query = cachedQuery.query;
    SqlCommand sqlCommand = query.getSqlCommand();
    if (sqlCommand != null) {
      ps.wantsGeneratedKeysAlways = sqlCommand.isReturningKeywordPresent();
    } else {
      // If composite query is given, just ignore "generated keys" arguments
    }
    return ps;
  }

  @Override
  public final Map<String,String> getParameterStatuses() {
    return queryExecutor.getParameterStatuses();
  }

  @Override
  public final @Nullable String getParameterStatus(String parameterName) {
    return queryExecutor.getParameterStatus(parameterName);
  }

  @Override
  public boolean getAdaptiveFetch() {
    return queryExecutor.getAdaptiveFetch();
  }

  @Override
  public void setAdaptiveFetch(boolean adaptiveFetch) {
    queryExecutor.setAdaptiveFetch(adaptiveFetch);
  }

  @Override
  public PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException {
    PGXmlFactoryFactory xmlFactoryFactory = this.xmlFactoryFactory;
    if (xmlFactoryFactory != null) {
      return xmlFactoryFactory;
    }
    if (xmlFactoryFactoryClass == null || xmlFactoryFactoryClass.equals("")) {
      xmlFactoryFactory = DefaultPGXmlFactoryFactory.INSTANCE;
    } else if (xmlFactoryFactoryClass.equals("LEGACY_INSECURE")) {
      xmlFactoryFactory = LegacyInsecurePGXmlFactoryFactory.INSTANCE;
    } else {
      Class<?> clazz;
      try {
        clazz = Class.forName(xmlFactoryFactoryClass);
      } catch (ClassNotFoundException ex) {
        throw new PSQLException(
            GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass),
            PSQLState.INVALID_PARAMETER_VALUE, ex);
      }
      if (!clazz.isAssignableFrom(PGXmlFactoryFactory.class)) {
        throw new PSQLException(
            GT.tr("Connection property xmlFactoryFactory must implement PGXmlFactoryFactory: {0}", xmlFactoryFactoryClass),
            PSQLState.INVALID_PARAMETER_VALUE);
      }
      try {
        xmlFactoryFactory = (PGXmlFactoryFactory) clazz.newInstance();
      } catch (Exception ex) {
        throw new PSQLException(
            GT.tr("Could not instantiate xmlFactoryFactory: {0}", xmlFactoryFactoryClass),
            PSQLState.INVALID_PARAMETER_VALUE, ex);
      }
    }
    this.xmlFactoryFactory = xmlFactoryFactory;
    return xmlFactoryFactory;
  }
}


text:
require 'test_helper'
require 'rubycritic/core/smell'

describe RubyCritic::Smell do
  describe 'attribute readers' do
    before do
      @locations = [RubyCritic::Location.new('./foo', '42')]
      @context = '#bar'
      @message = 'This smells'
      @score = 0
      @type = :complexity
      @smell = RubyCritic::Smell.new(
        locations: @locations,
        context: @context,
        message: @message,
        score: @score,
        type: @type
      )
    end

    it 'has a context reader' do
      _(@smell.context).must_equal @context
    end

    it 'has a locations reader' do
      _(@smell.locations).must_equal @locations
    end

    it 'has a message reader' do
      _(@smell.message).must_equal @message
    end

    it 'has a score reader' do
      _(@smell.score).must_equal @score
    end

    it 'has a type reader' do
      _(@smell.type).must_equal @type
    end
  end

  describe '#at_location?' do
    it 'returns true if the smell has a location that matches the location passed as argument' do
      location = RubyCritic::Location.new('./foo', '42')
      smell = RubyCritic::Smell.new(locations: [location])
      _(smell.at_location?(location)).must_equal true
    end
  end

  describe '#multiple_locations?' do
    it 'returns true if the smell has more than one location' do
      location1 = RubyCritic::Location.new('./foo', '42')
      location2 = RubyCritic::Location.new('./foo', '23')
      smell = RubyCritic::Smell.new(locations: [location1, location2])
      _(smell.multiple_locations?).must_equal true
    end
  end

  describe '#==' do
    it 'returns true if two smells have the same base attributes' do
      attributes = {
        context: '#bar',
        message: 'This smells',
        score: 0,
        type: :complexity
      }
      smell1 = RubyCritic::Smell.new(attributes)
      smell2 = RubyCritic::Smell.new(attributes)
      _(smell1).must_equal smell2
    end
  end

  describe '#doc_url' do
    it 'handles one word type names for reek smells' do
      smell = RubyCritic::Smell.new(type: 'Complexity', analyser: 'reek')

      _(smell.doc_url).must_equal('https://github.com/troessner/reek/blob/master/docs/Complexity.md')
    end

    it 'handles multiple word type names for reek smells' do
      smell = RubyCritic::Smell.new(type: 'TooManyStatements', analyser: 'reek')

      _(smell.doc_url).must_equal('https://github.com/troessner/reek/blob/master/docs/Too-Many-Statements.md')
    end

    it 'handles flay smells' do
      smell = RubyCritic::Smell.new(type: 'DuplicateCode', analyser: 'flay')

      _(smell.doc_url).must_equal('http://docs.seattlerb.org/flay/')
    end

    it 'handles flog smells' do
      smell = RubyCritic::Smell.new(type: 'VeryHighComplexity', analyser: 'flog')

      _(smell.doc_url).must_equal('http://docs.seattlerb.org/flog/')
    end

    it 'raises an error for unknown analysers' do
      smell = RubyCritic::Smell.new(type: 'FooSmell', analyser: 'foo')
      assert_raises { smell.doc_url }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
{% extends 'pages/base.html' %}

{% block navbar_breadcrumb %}
{% endblock navbar_breadcrumb %}

{% block maintitle %}
  Disabled Exploration - Oppia
{% endblock maintitle %}

{% block content %}

{% endblock %}


text:
import { SettingsFromSchema } from "~/core/game/base/base-game-settings";
import { UnknownObject } from "~/utils";
import { BaseClasses } from "./";

// <<-- Creer-Merge: imports -->>
// any additional imports you want can be placed here safely between creer runs
// <<-- /Creer-Merge: imports -->>

/**
 * The settings manager for the Anarchy game.
 */
export class AnarchyGameSettingsManager extends BaseClasses.GameSettings {
    /**
     * This describes the structure of the game settings, and is used to
     * generate the values, as well as basic type and range checking.
     */
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    public get schema() {
        return this.makeSchema({
            // HACK: `super` should work. but schema is undefined on it at run time.
            // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
            ...(super.schema || (this as any).schema),

            // Anarchy game specific settings
            // <<-- Creer-Merge: schema -->>

            mapWidth: {
                default: 40,
                min: 2,
                description:
                    "The width (in Buildings) for the game map to be initialized to.",
            },
            mapHeight: {
                default: 20,
                min: 2,
                description:
                    "The height (in Buildings) for the game map to be initialized to.",
            },
            maxFire: {
                default: 20,
                min: 1,
                description:
                    "The maximum amount of fire value for any Building.",
            },
            baseBribesPerTurn: {
                default: 10,
                min: 1,
                description:
                    "How many bribes players get at the beginning of " +
                    "their turn, not counting their burned down Buildings.",
            },
            buildingStartingHealth: {
                default: 100,
                min: 1,
                description:
                    "The amount of health buildings start the game with.",
            },
            headquartersHealthScalar: {
                default: 3,
                min: 1,
                description:
                    "How much health to scale (multiply a Headquarters health by",
            },
            maxForecastIntensity: {
                default: 10,
                min: 1,
                description:
                    "The maximum intensity to allow Forecasts to have.",
            },
            firePerTurnReduction: {
                default: 1,
                min: 0,
                description: "How much fire to remove per turn.",
            },
            exposurePerTurnReduction: {
                default: 10,
                min: 0,
                description: "How much exposure to remove per turn.",
            },

            // <<-- /Creer-Merge: schema -->>

            // Base settings
            playerStartingTime: {
                // <<-- Creer-Merge: player-starting-time -->>
                default: 6e10, // 1 min in ns
                // <<-- /Creer-Merge: player-starting-time -->>
                min: 0,
                description: "The starting time (in ns) for each player.",
            },

            // Turn based settings
            timeAddedPerTurn: {
                // <<-- Creer-Merge: time-added-per-turn -->>
                default: 1e9, // 1 sec in ns,
                // <<-- /Creer-Merge: time-added-per-turn -->>
                min: 0,
                description:
                    "The amount of time (in nano-seconds) to add after " +
                    "each player performs a turn.",
            },
            maxTurns: {
                // <<-- Creer-Merge: max-turns -->>
                default: 200,
                // <<-- /Creer-Merge: max-turns -->>
                min: 1,
                description:
                    "The maximum number of turns before the game " +
                    "is force ended and a winner is determined.",
            },
        });
    }

    /**
     * The current values for the game's settings.
     */
    public values!: SettingsFromSchema<AnarchyGameSettingsManager["schema"]>;

    /**
     * Try to invalidate all the game settings here, so invalid values do not
     * reach the game.
     *
     * @param someSettings - A subset of settings that will be tested.
     * @returns An error if the settings fail to validate, otherwise the
     * valid game settings for this game.
     */
    protected invalidate(someSettings: UnknownObject): UnknownObject | Error {
        const invalidated = super.invalidate(someSettings);
        if (invalidated instanceof Error) {
            return invalidated;
        }

        const settings = { ...this.values, ...someSettings, ...invalidated };

        // <<-- Creer-Merge: invalidate -->>

        // Write logic here to check the values in `settings`. If there is a
        // problem with the values a player sent, return an error with a string
        // describing why their value(s) are wrong

        // <<-- /Creer-Merge: invalidate -->>

        return settings;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII" />
    <title>BasicStream - SeqAn API Documentation</title>

      <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="lib/bootstrap-multiselect/css/bootstrap-multiselect.css" type="text/css" media="screen" charset="utf-8" />

      <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />
      <link rel="stylesheet" href="css/common.less.css" type="text/css" media="screen" charset="utf-8" />

  Fn<> BasicStream

Return the stream type to read or write values.

    Defined in

      <seqan/basic.h>

    Signature

      BasicStream<TValue, TDirection[, TTraits]>::Type;

Template Parameters

        TValue
        The value type of the stream.

        TDirection
        The direction of the stream, one of the DirectionTags.

        TTraits
        The traits to use for the values, defaults to <tt>std::char_traits<TValue></tt>.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Dox Sources

/*!
 * @mfn BasicStream
 *
 * @headerfile <seqan/basic.h>
 *
 * @brief Return the stream type to read or write values.
 *
 * @signature BasicStream<TValue, TDirection[, TTraits]>::Type;
 *
 * @tparam TValue The value type of the stream.
 * @tparam TDirection The direction of the stream, one of the @link
 *                    DirectionTags @endlink.
 * @tparam TTraits The traits to use for the values, defaults to
 *                 <tt>std::char_traits&lt;TValue&gt;</tt>.
 */

        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>


text:
### Links to the various repositories of various IoT-related organizations
1. IPSO Alliance: https://github.com/IPSO-Alliance/pub


text: Reach and organize your volunteers


text:
var ConsoleLogger, LOG_LEVEL, MongoClient, Server, XML, dashPostUrl, dgram, elecEventsLogged, gasEventsLogged, gasServer, lastValTimeElec, lastValTimeHeat, logger, moment, mongoClient, mongoDBEnergyManager, mongoHost, mongoPort, numDashPostsOk, owlServer, postData, request, secsBetweenValsElec, secsBetweenValsHeat, tempEventsLogged, tempServer,
  modulo = function(a, b) { return (+a % (b = +b) + b) % b; };

request = require('request');

MongoClient = require("mongodb").MongoClient;

Server = require("mongodb").Server;

moment = require("moment");

XML = require('xml2json');

mongoHost = "macallan.local";

mongoPort = 27017;

dashPostUrl = "http://domoticzoff:5098/timeSeriesData/";

LOG_LEVEL = "2Info";

ConsoleLogger = (function() {
  function ConsoleLogger() {}

  ConsoleLogger.prototype.debug = function(strToShow) {
    if (LOG_LEVEL >= "3Debug") {
      return console.log(moment().format(), strToShow);
    }
  };

  ConsoleLogger.prototype.info = function(strToShow) {
    if (LOG_LEVEL >= "2Info") {
      return console.info(moment().format(), strToShow);
    }
  };

  ConsoleLogger.prototype.error = function(strToShow) {
    if (LOG_LEVEL >= "1Warn") {
      return console.error(moment().format(), strToShow);
    }
  };

  ConsoleLogger.prototype.warn = function(strToShow) {
    return console.warn(moment().format(), strToShow);
  };

  return ConsoleLogger;

})();

logger = new ConsoleLogger();

numDashPostsOk = 0;

mongoClient = new MongoClient(new Server(mongoHost, mongoPort));

mongoDBEnergyManager = null;

mongoClient.open(function(err, mongoClient) {
  if (!mongoClient) {
    logger.error("Error! MongoDB must be running ... Shutting down");
    process.exit(1);
  }
  mongoDBEnergyManager = mongoClient.db("EnergyManager");
  logger.info("Connected to Mongo");
});

logger.info("Starting Energy Monitoring (Elec, Temperature, Gas, etc)");

lastValTimeElec = 0;

lastValTimeHeat = 0;

secsBetweenValsElec = 120;

secsBetweenValsHeat = 120;

elecEventsLogged = 0;

gasEventsLogged = 0;

tempEventsLogged = 0;

dgram = require("dgram");

owlServer = dgram.createSocket("udp4");

owlServer.on("error", function(err) {
  logger.error("OWL Server Error " + err.stack);
});

owlServer.on("message", function(msg, rinfo) {
  var chanInfo, curEpochSecs, e, i, ignoreThis, jsonData, jsonStr, len, outData, ref;
  curEpochSecs = Math.floor(new Date().getTime() / 1000);
  ignoreThis = curEpochSecs < lastValTimeElec + secsBetweenValsElec;
  logger.debug("Elec from " + rinfo.address + ":" + rinfo.port + (ignoreThis ? " (ignoring)" : " (using)"));
  if (ignoreThis) {
    return;
  }
  lastValTimeElec = curEpochSecs;
  jsonStr = XML.toJson(msg);
  jsonData = JSON.parse(jsonStr);
  if ("electricity" in jsonData && "chan" in jsonData.electricity) {
    e = [];
    ref = jsonData.electricity.chan;
    for (i = 0, len = ref.length; i < len; i++) {
      chanInfo = ref[i];
      if ("curr" in chanInfo) {
        e.push({
          n: "ch" + chanInfo.id + "Cur",
          v: chanInfo.curr.$t,
          u: "W"
        });
      }
      if ("day" in chanInfo) {
        e.push({
          n: "ch" + chanInfo.id + "Day",
          v: chanInfo.day.$t,
          u: "Wh"
        });
      }
    }
    outData = {
      e: e,
      bt: curEpochSecs
    };
    elecEventsLogged += 1;
    logger.debug("Posting " + JSON.stringify(outData));
    postData('ElecUseRawDaily', outData);
  }
});

owlServer.on("listening", function() {
  var address;
  address = owlServer.address();
  logger.info("owlServer listening " + address.address + ":" + address.port);
});

owlServer.bind(22600, function() {
  owlServer.addMembership('224.192.32.19');
});

gasServer = dgram.createSocket("udp4");

gasServer.on("error", function(err) {
  logger.error("GasMonitor Error " + error.stack);
});

gasServer.on("message", function(msg, rinfo) {
  var curEpochSecs, outData;
  logger.debug("Gas from " + rinfo.address + ":" + rinfo.port);
  curEpochSecs = Math.floor(new Date().getTime() / 1000);
  outData = JSON.parse(msg);
  if (!("bt" in outData) || outData["bt"] < 1000000000) {
    outData["bt"] = curEpochSecs;
  }
  gasEventsLogged += 1;
  postData('GasUseRawDaily', outData);
});

gasServer.on("listening", function() {
  var address;
  address = gasServer.address();
  logger.info("gasServer listening " + address.address + ":" + address.port);
});

gasServer.bind(42853);

tempServer = dgram.createSocket("udp4");

tempServer.on("error", function(err) {
  logger.error("TemperatureServer error:\n" + err.stack);
});

tempServer.on("message", function(msg, rinfo) {
  var curEpochSecs, outData;
  logger.debug("temperature " + msg + " from " + rinfo.address + ":" + rinfo.port);
  curEpochSecs = Math.floor(new Date().getTime() / 1000);
  outData = JSON.parse(msg);
  if (!("bt" in outData) || outData["bt"] < 1000000000) {
    outData["bt"] = curEpochSecs;
  }
  tempEventsLogged += 1;
  postData('RoomTempRawDaily', outData);
});

tempServer.on("listening", function() {
  var address;
  address = tempServer.address();
  logger.info("temperatureServer listening " + address.address + ":" + address.port);
});

tempServer.bind(42854);

postData = function(dataSeriesBase, dataToPost) {
  var dayNameStr, options, seriesName, totalEvents;
  totalEvents = elecEventsLogged + gasEventsLogged + tempEventsLogged;
  if ((modulo(totalEvents, 100)) === 0) {
    logger.info("Logged: " + elecEventsLogged + " Elec, " + gasEventsLogged + " Gas, " + tempEventsLogged + " Temp");
  }
  dayNameStr = moment(dataToPost["bt"] * 1000).format("YYYYMMDD");
  seriesName = dataSeriesBase + "_" + dayNameStr;
  logger.debug("Storing " + seriesName + " = " + JSON.stringify(dataToPost));
  if (mongoDBEnergyManager != null) {
    mongoDBEnergyManager.collection(seriesName).insert(dataToPost, function(err, doc) {
      var errorStr;
      if (err !== null) {
        errorStr = moment().format() + " mongo failed to update " + err;
        logger.error(errorStr);
      } else {
        logger.debug(moment().format() + " " + dataSeriesBase + " Updated ok");
      }
    });
  }
  options = {
    uri: dashPostUrl,
    method: 'POST',
    json: true,
    headers: {
      "content-type": "application/json"
    },
    body: dataToPost
  };
  request(options, function(error, response, body) {
    if (error != null) {
      logger.error("Failed to post data to " + dashPostUrl + ", err: " + error);
    } else {
      if (response.statusCode === 200) {
        numDashPostsOk++;
        if ((modulo(numDashPostsOk, 100)) === 0) {
          logger.info(numDashPostsOk + " Dash posts completed ok");
        }
      } else {
        logger.error("Dash server responded with " + response.statusCode + ", " + body);
      }
    }
  });
};


text:
package de.ppi.samples.fuwesta.frontend;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import de.ppi.fuwesta.spring.mvc.util.URLCleaner;
import de.ppi.fuwesta.spring.mvc.util.UrlDefinitionsToMessages.ParamFormat;

/**
 * List of all URLs.
 *
 */
// CSOFF: InterfaceIsType You must give the Annotations Strings and can't use
// Enums.
public final class URL {

    /**
     * Prefix für Redirect-Urls.
     */
    private static final String REDIRECT_PREFIX = "redirect:";

    /**
     * Map which stores the UriComponents.
     */
    private static final Map<String, UriComponents> URI_MAP =
            new ConcurrentHashMap<String, UriComponents>();

    /**
     * Home-Url.
     */
    public static final String HOME = "/home";

    /**
     *
     * URLs for authentification.
     *
     */
    public interface Auth {

        /**
         * Login-Url.
         */
        String LOGIN = "/login";

        /**
         * Not authorized.
         */
        String UNAUTHORIZED = "/unauthorized";

    }

    /**
     * Definition for paginating.
     *
     */
    public interface Page {

        /**
         * Parameter for the number of the page.
         */
        @ParamFormat
        String P_NUMBER = "page";

        /**
         * Parameter for the size of the page.
         */
        @ParamFormat
        String P_SIZE = "size";

        /**
         * Parameter-Group for number and size of the page.
         */
        String PG_NUMBER_SIZE = P_NUMBER + ", " + P_SIZE;
    }

    /**
     * All URLS for the User.
     *
     */
    public interface User {
        /**
         * User-Url.
         */
        String HOME = "/user";

        /**
         * Parametername for the user-id.
         */
        @ParamFormat
        String P_USERID = "user_idn";

        /**
         * Edit-User-Url.
         */
        String EDIT = HOME + "/edit/{" + P_USERID + "}";

        /**
         * Show-User-Url.
         */
        String SHOW = HOME + "/show/{" + P_USERID + "}";

        /**
         * Delete-User-Url.
         */
        String DELETE = HOME + "/delete/{" + P_USERID + "}";

        /** List User-URL. */
        String LIST = HOME + "/list";

        /** Create User-URL. */
        String CREATE = HOME + "/create";
    }

    /**
     * All URLS for the {@link de.ppi.fuwesta.samples.springmvc.model.Post}.
     *
     */
    public interface Post {
        /**
         * Post-Url.
         */
        String HOME = "/post";

        /**
         * Parameter for id of the post.
         */
        @ParamFormat
        String P_POSTID = "post_idn";

        /**
         * Edit-Post-Url.
         */
        String EDIT = HOME + "/edit/{" + P_POSTID + "}";

        /**
         * Partial Edit-Post-Url.
         */
        String PARTIALEDIT = HOME + "/partialedit/{" + P_POSTID + "}";

        /**
         * Show-Post-Url.
         */
        String SHOW = HOME + "/show/{" + P_POSTID + "}";

        /**
         * Delete-Post-Url.
         */
        String DELETE = HOME + "/delete/{" + P_POSTID + "}";

        /** List Post-URL. */
        String LIST = HOME + "/list";

        /** Create Post-URL. */
        String CREATE = HOME + "/create";
    }

    /**
     * All URLS for the {@link de.ppi.fuwesta.samples.springmvc.model.Tag}.
     *
     */
    public interface Tag {
        /**
         * Tag-Url.
         */
        String HOME = "/tag";

        /**
         * Parameter for the if of the tag.
         */
        @ParamFormat
        String P_TAGID = "tag_idn";

        /**
         * Edit-Tag-Url.
         */
        String EDIT = HOME + "/edit/{" + P_TAGID + "}";

        /**
         * Show-Tag-Url.
         */
        String SHOW = HOME + "/show/{" + P_TAGID + "}";

        /**
         * Delete-Tag-Url.
         */
        String DELETE = HOME + "/delete/{" + P_TAGID + "}";

        /** List Tag-URL. */
        String LIST = HOME + "/list";

        /** Create Tag-URL. */
        String CREATE = HOME + "/create";
    }

    /**
     * Replace the parameter in the URL with the given value.
     *
     * @param url the URL.
     * @param parameter the parameter
     * @return the URL with parameters filled in
     */
    public static String filledURL(String url, Object parameter) {
        final UriComponents uricomponent = getUriComponent(url);
        return uricomponent.expand(parameter).encode().toUriString();
    }

    /**
     * Encode the given URL.
     *
     * @param url the URL.
     * @return the URL with parameters filled in
     */
    public static String filledURL(String url) {
        final UriComponents uricomponent = getUriComponent(url);
        return uricomponent.expand().encode().toUriString();
    }

    /**
     * Replace all parameters in the URL with the given values.
     *
     * @param url the URL.
     * @param keyValuePairs the parameters as pair of name and value.
     * @return the URL with parameters filled in
     */
    public static String filledURLWithNamedParams(String url,
            Object... keyValuePairs) {
        if ((keyValuePairs == null) || (keyValuePairs.length == 0)) {
            return url;
        }
        if (keyValuePairs.length % 2 != 0) {
            throw new IllegalArgumentException(
                    "The array has to be of an even size - size is "
                            + keyValuePairs.length);
        }

        final Map<String, Object> values = new HashMap<String, Object>();

        for (int x = 0; x < keyValuePairs.length; x += 2) {
            values.put((String) keyValuePairs[x], keyValuePairs[x + 1]);
        }

        final UriComponents uricomponent = getUriComponent(url);
        return uricomponent.expand(values).encode().toUriString();
    }

    /**
     * Give a {@link UriComponents} to the URL.
     *
     * @param url a url as String
     * @return the {@link UriComponents}
     */
    private static UriComponents getUriComponent(String url) {
        if (!URI_MAP.containsKey(url)) {
            URI_MAP.put(
                    url,
                    UriComponentsBuilder.fromUriString(
                            URLCleaner.removeRegexpFromUrl(url)).build());
        }

        return URI_MAP.get(url);
    }

    /**
     * Replace all parameters in the URL with the given values.
     *
     * @param url the URL.
     * @param parameters the parameters
     * @return the URL with parameters filled in
     */
    public static String filledURL(String url, Map<String, ?> parameters) {
        if ((parameters == null) || (parameters.size() == 0)) {
            return url;
        }

        final UriComponents uricomponent = getUriComponent(url);
        return uricomponent.expand(parameters).encode().toUriString();
    }

    /**
     * Replace all parameters in the URL with the given values and make a
     * redirect.
     *
     * @param url the URL.
     * @param parameter the parameter
     * @return the redirect URL with parameters filled in
     */
    public static String redirect(String url, Object parameter) {
        return REDIRECT_PREFIX + filledURL(url, parameter);
    }

    /**
     * Replace all parameters in the URL with the given values and make a
     * redirect.
     *
     * @param url the URL.
     * @return the redirect URL with parameters filled in
     */
    public static String redirect(String url) {
        return REDIRECT_PREFIX + filledURL(url);
    }

    /**
     * Replace all parameters in the URL with the given values and make a
     * redirect.
     *
     * @param url the URL.
     * @param keyValuePairs the parameters as pair of name and value
     * @return the redirect URL with parameters filled in
     */
    public static String redirectWithNamedParams(String url,
            Object... keyValuePairs) {
        return REDIRECT_PREFIX + filledURLWithNamedParams(url, keyValuePairs);
    }

    /**
     * Replace all parameters in the URL with the given values and make a
     * redirect.
     *
     * @param url the URL.
     * @param namedParameters the parameters
     * @return the redirect URL with parameters filled in.
     */
    public static String redirect(String url,
            Map<String, String> namedParameters) {
        return REDIRECT_PREFIX + filledURL(url, namedParameters);
    }

    /**
     * Initiates an object of type URL.
     */
    private URL() {
        // UTILITY-CONSTRUCTOR
    };

}
// CSON: InterfaceIsType


text:
import requests
import re
from lxml import etree
from HTMLParser import HTMLParser

from regenesis.cube import Cube

QUADER = re.compile(r"<quaderDaten>\* (.*)<\/quaderDaten>", re.S | re.M)

def fetch_index(catalog):
    for i in range(10, 100):
        params = [
            ('method', 'DatenKatalog'),
            ('kennung', catalog.get('username')),
            ('passwort', catalog.get('password')),
            ('filter', '%s*' % i),
            ('bereich', 'Alle'),
            ('listenLaenge', '500'),
            ('sprache', 'de')
            ]
        doc = requests.get(catalog.get('index_url'), params=params)
        doc = etree.fromstring(doc.content)
        for entry in doc.findall('.//datenKatalogEintraege/datenKatalogEintraege'):
            #print [entry.findtext('./code')]
            yield entry.findtext('./code')

def fetch_cube(catalog, name):
    params = [
        ('method', 'DatenExport'),
        ('kennung', catalog.get('username')),
        ('passwort', catalog.get('password')),
        ('namen', name),
        ('bereich', 'Alle'),
        ('format', 'csv'),
        ('werte', True),
        ('metadaten', True),
        ('zusatz', True),
        ('startjahr', 1900),
        ('endjahr', ''),
        ('zeitscheiben', ''),
        ('inhalte', ''),
        ('regionalmerkmal', ''),
        ('regionalschluessel', ''),
        ('sachmerkmal', ''),
        ('sachschluessel', ''),
        ('sachmerkmal2', ''),
        ('sachschluessel2', ''),
        ('sachmerkmal3', ''),
        ('sachschluessel3', ''),
        ('stand', ''),
        ('sprache', 'de')
        ]
    doc = requests.get(catalog.get('export_url'), params=params)
    #print [doc.url]
    #doc = etree.fromstring(doc.content)
    #return doc.find('.//quaderDaten').text
    m = QUADER.search(doc.content)
    if m is None:
        print "NO CUBE CONTENT", catalog, name
        return
    return HTMLParser().unescape(m.group(1))
    #return Cube(name, data)


text:
<?xml version="1.0" encoding="UTF-8"?>
<para xmlns= "http://docbook.org/ns/docbook" version= "5.0">

Description of nova.conf file configuration options
        for compute nodes

    <col width= "50%"/>
    <col width= "50%"/>

            <para>Configuration option=Default value</para>
            <para>(Type) Description</para>

            <para>
                compute_driver=nova.virt.connection.get_connection </para>
            <para> (StrOpt) Driver to use for controlling
                virtualization </para>

            <para> console_host=MGG2WEDRJM </para>
            <para> (StrOpt) Console proxy host to use to connect to
                instances on this host. </para>

            <para> default_notification_level=INFO </para>
            <para> (StrOpt) Default notification level for outgoing
                notifications </para>

            <para> default_publisher_id=$host </para>
            <para> (StrOpt) Default publisher_id for outgoing
                notifications </para>

            <para> heal_instance_info_cache_interval=60 </para>
            <para> (IntOpt) Number of seconds between instance
                info_cache self healing updates </para>

            <para> host_state_interval=120 </para>
            <para> (IntOpt) Interval in seconds for querying the
                host status </para>

            <para> image_cache_manager_interval=40 </para>
            <para> (IntOpt) Number of periodic scheduler ticks to
                wait between runs of the image cache manager.
            </para>

            <para> instances_path=$state_path/instances </para>
            <para> (StrOpt) where instances are stored on disk </para>

            <para> reboot_timeout=0 </para>
            <para> (IntOpt) Automatically hard reboot an instance if
                it has been stuck in a rebooting state longer than
                N seconds. Set to 0 to disable. </para>

            <para> rescue_timeout=0 </para>
            <para> (IntOpt) Automatically unrescue an instance after
                N seconds. Set to 0 to disable. </para>

            <para> resize_confirm_window=0 </para>
            <para> (IntOpt) Automatically confirm resizes after N
                seconds. Set to 0 to disable. </para>

            <para> running_deleted_instance_action=log </para>
            <para> (StrOpt) Action to take if a running deleted
                instance is detected.Valid options are 'noop',
                'log' and 'reap'. Set to 'noop' to disable. </para>

            <para> running_deleted_instance_poll_interval=30 </para>
            <para> (IntOpt) Number of periodic scheduler ticks to
                wait between runs of the cleanup task. </para>

            <para> running_deleted_instance_timeout=0 </para>
            <para> (IntOpt) Number of seconds after being deleted
                when a running instance should be considered
                eligible for cleanup. </para>

</para>


text:
#include <sys/stat.h>
#undef NDEBUG
#include <cassert>
#include <chrono>
#include <fstream>
#include <utility>
#include <memory>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include "utils/file/FileUtils.h"
#include "utils/StringUtils.h"
#include "core/Core.h"
#include "core/logging/Logger.h"
#include "core/ProcessGroup.h"
#include "core/yaml/YamlConfiguration.h"
#include "FlowController.h"
#include "properties/Configure.h"
#include "../unit/ProvenanceTestHelper.h"
#include "io/StreamFactory.h"
#include "../TestBase.h"

void waitToVerifyProcessor() {
  std::this_thread::sleep_for(std::chrono::seconds(2));
}

int main(int argc, char **argv) {
  std::string test_file_location;
  if (argc > 1) {
    test_file_location = argv[1];
  }
  // need to change test to not use temp dir
#ifndef WIN32
  mkdir("/tmp/aljs39/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  mkdir("content_repository", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  LogTestController::getInstance().setDebug<core::ProcessGroup>();

  std::shared_ptr<minifi::Configure> configuration = std::make_shared<minifi::Configure>();
  std::shared_ptr<core::Repository> test_repo = std::make_shared<TestRepository>();
  std::shared_ptr<core::Repository> test_flow_repo = std::make_shared<TestFlowRepository>();

  configuration->set(minifi::Configure::nifi_flow_configuration_file, test_file_location);
  std::shared_ptr<minifi::io::StreamFactory> stream_factory = minifi::io::StreamFactory::getInstance(configuration);
  std::shared_ptr<core::ContentRepository> content_repo = std::make_shared<core::repository::VolatileContentRepository>();
  std::unique_ptr<core::FlowConfiguration> yaml_ptr = std::unique_ptr<core::YamlConfiguration>(
      new core::YamlConfiguration(test_repo, test_repo, content_repo, stream_factory, configuration, test_file_location));
  std::shared_ptr<TestRepository> repo = std::static_pointer_cast<TestRepository>(test_repo);

  std::shared_ptr<minifi::FlowController> controller = std::make_shared<minifi::FlowController>(test_repo, test_flow_repo, configuration, std::move(yaml_ptr), content_repo, DEFAULT_ROOT_GROUP_NAME,
                                                                                true);

  core::YamlConfiguration yaml_config(test_repo, test_repo, content_repo, stream_factory, configuration, test_file_location);

  std::unique_ptr<core::ProcessGroup> ptr = yaml_config.getRoot(test_file_location);
  std::shared_ptr<core::ProcessGroup> pg = std::shared_ptr<core::ProcessGroup>(ptr.get());
  ptr.release();
  std::shared_ptr<org::apache::nifi::minifi::io::SocketContext> socket_context = std::make_shared<org::apache::nifi::minifi::io::SocketContext>(std::make_shared<minifi::Configure>());
  org::apache::nifi::minifi::io::ServerSocket server(socket_context, "localhost", 10005, 1);

  controller->load();
  controller->start();
  waitToVerifyProcessor();

  controller->waitUnload(60000);
  std::string logs = LogTestController::getInstance().log_output.str();
  assert(logs.find("Add processor SiteToSiteProvenanceReportingTask into process group MiNiFi Flow") != std::string::npos);
  LogTestController::getInstance().reset();
  rmdir("./content_repository");
  rmdir("/tmp/aljs39/");
#endif
  return 0;
}


text:
<?php

namespace DvsaCommon\Dto\Organisation;

use DvsaCommon\Dto\AbstractDataTransferObject;
use DvsaCommon\Dto\Person\PersonDto;
use DvsaCommon\Enum\BusinessRoleStatusCode;

/**
 * Class OrganisationPositionDto
 *
 * @package DvsaCommon\Dto\Organisation
 */
class OrganisationPositionDto extends AbstractDataTransferObject
{
    private $person;

    /**
     * @var string $role
     */
    private $role;

    /** @var int $id */
    private $id;

    /** @var  int $status */
    private $status;

    /** @var  string $actionedOn */
    private $actionedOn;

    /**
     * @param string $role
     * @see OrganisationBusinessRoleCode
     *
     * @return OrganisationPositionDto
     */
    public function setRole($role)
    {
        $this->role = $role;
        return $this;
    }

    /**
     * @return string
     * @see OrganisationBusinessRoleCode
     */
    public function getRole()
    {
        return $this->role;
    }

    /**
     * @param PersonDto $person
     *
     * @return OrganisationPositionDto
     */
    public function setPerson($person)
    {
        $this->person = $person;
        return $this;
    }

    /**
     * @return PersonDto
     */
    public function getPerson()
    {
        return $this->person;
    }

    /**
     * @param int $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $status
     *
     * @return $this
     */
    public function setStatus($status)
    {
        $this->status = $status;
        return $this;
    }

    /**
     * @return int
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param string $actionedOn
     *
     * @return $this
     */
    public function setActionedOn($actionedOn)
    {
        $this->actionedOn = $actionedOn;
        return $this;
    }

    /**
     * @return string
     */
    public function getActionedOn()
    {
        return $this->actionedOn;
    }

    public function isPending()
    {
        return $this->status == BusinessRoleStatusCode::PENDING;
    }

    public function isActive()
    {
        return $this->status == BusinessRoleStatusCode::ACTIVE;
    }
}


text:
package com.twitter.finatra.http.integration.tweetexample.main.controllers

import com.twitter.finagle.http.Request
import com.twitter.finatra.http.Controller
import com.twitter.finatra.http.integration.tweetexample.main.services.admin.UserService
import com.twitter.finatra.test.{Prod, Staging}
import javax.inject.Inject

class AdminController @Inject()(
  @Prod prodUsers: UserService,
  @Staging stagingUsers: UserService)
  extends Controller {

  get("/admin/finatra/yo") { request: Request =>
    "yo yo"
  }

  get("/admin/finatra/users/:id") { request: Request =>
    val userId = request.params("id")
    prodUsers.get(userId) + ", " +
      stagingUsers.get(userId)
  }
}


text:
class NamedPipe;

class EventLoop
{
public:
    EventLoop();
    virtual ~EventLoop();
    void run();

protected:
    NamedPipe *createNamedPipe();
    void setPollInterval(int ms);
    void shutdown();
    virtual void onPollTimeout();
    virtual void onPipeIo(NamedPipe *namedPipe);

private:
    bool m_exiting;
    std::vector<NamedPipe*> m_pipes;
    int m_pollInterval;
};

#endif // EVENTLOOP_H


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="0" key="scope"/>

		<list key="Search.processedPageIds">
			<item value="org.eclipse.rse.internal.files.ui.search.searchPage"/>
			<item value="org.eclipse.search.internal.ui.text.TextSearchPage"/>
			<item value="org.eclipse.mylyn.tasks.ui.search.page"/>
			<item value="org.eclipse.jdt.ui.JavaSearchPage"/>
			<item value="org.eclipse.wst.jsdt.ui.JavaSearchPage"/>
			<item value="org.eclipse.pde.internal.ui.search.SearchPage"/>
		</list>
		<list key="Search.enabledPageIds">
			<item value="org.eclipse.rse.internal.files.ui.search.searchPage"/>
			<item value="org.eclipse.search.internal.ui.text.TextSearchPage"/>
			<item value="org.eclipse.mylyn.tasks.ui.search.page"/>
			<item value="org.eclipse.jdt.ui.JavaSearchPage"/>
			<item value="org.eclipse.wst.jsdt.ui.JavaSearchPage"/>
			<item value="org.eclipse.pde.internal.ui.search.SearchPage"/>
		</list>

		<item value="org.eclipse.jdt.ui.JavaSearchPage" key="PREVIOUS_PAGE"/>

		<item value="510" key="DIALOG_WIDTH"/>
		<item value="1|Segoe UI|9.0|0|WINDOWS|1|-12|0|0|0|400|0|0|0|1|0|0|0|0|Segoe UI" key="DIALOG_FONT_NAME"/>
		<item value="450" key="DIALOG_HEIGHT"/>
		<item value="436" key="DIALOG_X_ORIGIN"/>
		<item value="72" key="DIALOG_Y_ORIGIN"/>


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.xml">
    <module_version install_time="1416340434990" last="true" origin="installer" specification_version="1.27.1">
        <file crc="4280234301" name="config/Modules/org-netbeans-modules-xml.xml"/>
        <file crc="2701807086" name="modules/locale/org-netbeans-modules-xml_ja.jar"/>
        <file crc="86646877" name="modules/locale/org-netbeans-modules-xml_pt_BR.jar"/>
        <file crc="107556815" name="modules/locale/org-netbeans-modules-xml_ru.jar"/>
        <file crc="1801692524" name="modules/locale/org-netbeans-modules-xml_zh_CN.jar"/>
        <file crc="1651679174" name="modules/org-netbeans-modules-xml.jar"/>
    </module_version>
</module>