/**
   * Returns a Result for setting the XML value designated by this SQLXML instance.
   *
   * <p>The systemID of the Result is implementation dependent.
   *
   * <p>The SQL XML object becomes not writeable when this method is called and may also become not
   * readable depending on implementation.
   *
   * <p>Note that SAX is a callback architecture and the returned SAXResult has a content handler
   * assigned that will receive the SAX events based on the contents of the XML. Call the content
   * handler with the contents of the XML document to assign the values.
   *
   * <pre>
   * SAXResult saxResult = sqlxml.setResult(SAXResult.class);
   * ContentHandler contentHandler = saxResult.getXMLReader().getContentHandler();
   * contentHandler.startDocument();
   * // set the XML elements and attributes into the result
   * contentHandler.endDocument();
   * </pre>
   *
   * @param resultClass The class of the result, or null. If resultClass is null, a vendor specific
   *     Result implementation will be returned. The following classes are supported at a minimum:
   *     <pre>
   *    javax.xml.transform.dom.DOMResult - returns a DOMResult
   *    javax.xml.transform.sax.SAXResult - returns a SAXResult
   *    javax.xml.transform.stax.StAXResult - returns a StAXResult
   *    javax.xml.transform.stream.StreamResult - returns a StreamResult
   * </pre>
   *
   * @return Returns a Result for setting the XML value.
   * @throws SQLException if there is an error processing the XML value or if this feature is not
   *     supported. The getCause() method of the exception may provide a more detailed exception,
   *     for example, if an XML parser exception occurs. An exception is thrown if the state is not
   *     writable.
   * @exception SQLFeatureNotSupportedException if the JDBC driver does not support this method
   * @since 1.6
   */
  public synchronized Result setResult(Class clazz) throws SQLException {
    checkClosed();
    checkWorkingWithResult();

    this.workingWithResult = true;
    this.asDOMResult = null;
    this.asSAXResult = null;
    this.saxToReaderConverter = null;
    this.stringRep = null;
    this.asStringWriter = null;
    this.asByteArrayOutputStream = null;

    if (clazz == null || clazz.equals(SAXResult.class)) {
      this.saxToReaderConverter = new SimpleSaxToReader();

      this.asSAXResult = new SAXResult(this.saxToReaderConverter);

      return this.asSAXResult;
    } else if (clazz.equals(DOMResult.class)) {

      this.asDOMResult = new DOMResult();
      return this.asDOMResult;

    } else if (clazz.equals(StreamResult.class)) {
      return new StreamResult(setCharacterStreamInternal());
    } else if (clazz.equals(StAXResult.class)) {
      try {
        if (this.outputFactory == null) {
          this.outputFactory = XMLOutputFactory.newInstance();
        }

        return new StAXResult(
            this.outputFactory.createXMLEventWriter(setCharacterStreamInternal()));
      } catch (XMLStreamException ex) {
        SQLException sqlEx =
            SQLError.createSQLException(
                ex.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(ex);

        throw sqlEx;
      }
    } else {
      throw SQLError.createSQLException(
          "XML Result of type \"" + clazz.toString() + "\" Not supported.",
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          this.exceptionInterceptor);
    }
  }
  /**
   * Get a description of the access rights for a table's columns.
   *
   * <p>Only privileges matching the column name criteria are returned. They are ordered by
   * COLUMN_NAME and PRIVILEGE.
   *
   * <p>Each privilige description has the following columns:
   *
   * <OL>
   *   <li><B>TABLE_CAT</B> String => table catalog (may be null)
   *   <li><B>TABLE_SCHEM</B> String => table schema (may be null)
   *   <li><B>TABLE_NAME</B> String => table name
   *   <li><B>COLUMN_NAME</B> String => column name
   *   <li><B>GRANTOR</B> => grantor of access (may be null)
   *   <li><B>GRANTEE</B> String => grantee of access
   *   <li><B>PRIVILEGE</B> String => name of access (SELECT, INSERT, UPDATE, REFRENCES, ...)
   *   <li><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted to grant to others; "NO" if
   *       not; null if unknown
   * </ol>
   *
   * @param catalog a catalog name; "" retrieves those without a catalog
   * @param schema a schema name; "" retrieves those without a schema
   * @param table a table name
   * @param columnNamePattern a column name pattern
   * @return ResultSet each row is a column privilege description
   * @throws SQLException if a database access error occurs
   * @see #getSearchStringEscape
   */
  public java.sql.ResultSet getColumnPrivileges(
      String catalog, String schema, String table, String columnNamePattern) throws SQLException {
    if (columnNamePattern == null) {
      if (this.conn.getNullNamePatternMatchesAll()) {
        columnNamePattern = "%";
      } else {
        throw SQLError.createSQLException(
            "Column name pattern can not be NULL or empty.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
      }
    }

    if (catalog == null) {
      if (this.conn.getNullCatalogMeansCurrent()) {
        catalog = this.database;
      }
    }

    String sql =
        "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME,"
            + "COLUMN_NAME, NULL AS GRANTOR, GRANTEE, PRIVILEGE_TYPE AS PRIVILEGE, IS_GRANTABLE FROM "
            + "INFORMATION_SCHEMA.COLUMN_PRIVILEGES WHERE "
            + "TABLE_SCHEMA LIKE ? AND "
            + "TABLE_NAME =? AND COLUMN_NAME LIKE ? ORDER BY "
            + "COLUMN_NAME, PRIVILEGE_TYPE";

    PreparedStatement pStmt = null;

    try {
      pStmt = prepareMetaDataSafeStatement(sql);

      if (catalog != null) {
        pStmt.setString(1, catalog);
      } else {
        pStmt.setString(1, "%");
      }

      pStmt.setString(2, table);
      pStmt.setString(3, columnNamePattern);

      ResultSet rs = executeMetadataQuery(pStmt);
      ((com.mysql.jdbc.ResultSet) rs)
          .redefineFieldsForDBMD(
              new Field[] {
                new Field("", "TABLE_CAT", Types.CHAR, 64),
                new Field("", "TABLE_SCHEM", Types.CHAR, 1),
                new Field("", "TABLE_NAME", Types.CHAR, 64),
                new Field("", "COLUMN_NAME", Types.CHAR, 64),
                new Field("", "GRANTOR", Types.CHAR, 77),
                new Field("", "GRANTEE", Types.CHAR, 77),
                new Field("", "PRIVILEGE", Types.CHAR, 64),
                new Field("", "IS_GRANTABLE", Types.CHAR, 3)
              });

      return rs;
    } finally {
      if (pStmt != null) {
        pStmt.close();
      }
    }
  }
  /**
   * Returns the next row.
   *
   * @return the next row value
   * @throws SQLException if a database error occurs
   */
  public ResultSetRow next() throws SQLException {
    if (this.fetchedRows == null && this.currentPositionInEntireResult != BEFORE_START_OF_ROWS) {
      throw SQLError.createSQLException(
          Messages.getString(
              "ResultSet.Operation_not_allowed_after_ResultSet_closed_144"), //$NON-NLS-1$
          SQLError.SQL_STATE_GENERAL_ERROR,
          mysql.getExceptionInterceptor());
    }

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

    this.currentPositionInEntireResult++;
    this.currentPositionInFetchedRows++;

    // Catch the forced scroll-passed-end
    if (this.fetchedRows != null && this.fetchedRows.size() == 0) {
      return null;
    }

    if (this.currentPositionInFetchedRows > (this.fetchedRows.size() - 1)) {
      fetchMoreRows();
      this.currentPositionInFetchedRows = 0;
    }

    ResultSetRow row = this.fetchedRows.get(this.currentPositionInFetchedRows);

    row.setMetadata(this.metadata);

    return row;
  }
  /**
   * Try to make a database connection to the given URL. The driver should return "null" if it
   * realizes it is the wrong kind of driver to connect to the given URL. This will be common, as
   * when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each
   * loaded driver in turn.
   *
   * <p>The driver should raise an SQLException if it is the right driver to connect to the given
   * URL, but has trouble connecting to the database.
   *
   * <p>The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as
   * connection arguments.
   *
   * <p>My protocol takes the form:
   *
   * <PRE>
   *
   * jdbc:mysql://host:port/database
   *
   * </PRE>
   *
   * @param url the URL of the database to connect to
   * @param info a list of arbitrary tag/value pairs as connection arguments
   * @return a connection to the URL or null if it isnt us
   * @exception SQLException if a database access error occurs
   * @see java.sql.Driver#connect
   */
  public java.sql.Connection connect(String url, Properties info) throws SQLException {
    if (url != null) {
      if (StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)) {
        return connectLoadBalanced(url, info);
      } else if (StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) {
        return connectReplicationConnection(url, info);
      }
    }

    Properties props = null;

    if ((props = parseURL(url, info)) == null) {
      return null;
    }

    try {
      Connection newConn =
          new com.mysql.jdbc.Connection(host(props), port(props), props, database(props), url);

      return newConn;
    } catch (SQLException sqlEx) {
      // Don't wrap SQLExceptions, throw
      // them un-changed.
      throw sqlEx;
    } catch (Exception ex) {
      throw SQLError.createSQLException(
          Messages.getString("NonRegisteringDriver.17") // $NON-NLS-1$
              + ex.toString()
              + Messages.getString("NonRegisteringDriver.18"), // $NON-NLS-1$
          SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE);
    }
  }
  /**
   * Parses hostPortPair in the form of [host][:port] into an array, with the element of index
   * HOST_NAME_INDEX being the host (or null if not specified), and the element of index
   * PORT_NUMBER_INDEX being the port (or null if not specified).
   *
   * @param hostPortPair host and port in form of of [host][:port]
   * @return array containing host and port as Strings
   * @throws SQLException if a parse error occurs
   */
  protected static String[] parseHostPortPair(String hostPortPair) throws SQLException {
    int portIndex = hostPortPair.indexOf(":"); // $NON-NLS-1$

    String[] splitValues = new String[2];

    String hostname = null;

    if (portIndex != -1) {
      if ((portIndex + 1) < hostPortPair.length()) {
        String portAsString = hostPortPair.substring(portIndex + 1);
        hostname = hostPortPair.substring(0, portIndex);

        splitValues[HOST_NAME_INDEX] = hostname;

        splitValues[PORT_NUMBER_INDEX] = portAsString;
      } else {
        throw SQLError.createSQLException(
            Messages.getString("NonRegisteringDriver.37"), // $NON-NLS-1$
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE);
      }
    } else {
      splitValues[HOST_NAME_INDEX] = hostPortPair;
      splitValues[PORT_NUMBER_INDEX] = null;
    }

    return splitValues;
  }
Exemple #6
0
  /**
   * Convenience method for turning a byte[] into a string with the given encoding.
   *
   * @param encoding the Java encoding name for the byte[] -> char conversion
   * @param conn the MySQLConnection that created the result set
   * @param value the String value as a series of bytes, encoded using "encoding"
   * @param offset where to start the decoding
   * @param length how many bytes to decode
   * @return the String as decoded from bytes with the given encoding
   * @throws SQLException if an error occurs
   */
  protected String getString(
      String encoding, MySQLConnection conn, byte[] value, int offset, int length)
      throws SQLException {
    String stringVal = null;

    if ((conn != null) && conn.getUseUnicode()) {
      try {
        if (encoding == null) {
          stringVal = StringUtils.toString(value);
        } else {
          SingleByteCharsetConverter converter = conn.getCharsetConverter(encoding);

          if (converter != null) {
            stringVal = converter.toString(value, offset, length);
          } else {
            stringVal = StringUtils.toString(value, offset, length, encoding);
          }
        }
      } catch (java.io.UnsupportedEncodingException E) {
        throw SQLError.createSQLException(
            Messages.getString("ResultSet.Unsupported_character_encoding____101") // $NON-NLS-1$
                + encoding
                + "'.",
            "0S100",
            this.exceptionInterceptor);
      }
    } else {
      stringVal = StringUtils.toAsciiString(value, offset, length);
    }

    return stringVal;
  }
  /**
   * Removes a host from the host list.
   *
   * @param host The host to be removed.
   * @throws SQLException
   */
  public synchronized void removeHost(String host) throws SQLException {
    if (this.connectionGroup != null) {
      if (this.connectionGroup.getInitialHosts().size() == 1
          && this.connectionGroup.getInitialHosts().contains(host)) {
        throw SQLError.createSQLException("Cannot remove only configured host.", null);
      }

      this.hostToRemove = host;

      if (host.equals(this.currentConnection.getHost())) {
        closeAllConnections();
      } else {
        this.connectionsToHostsMap.remove(this.liveConnections.remove(host));
        Integer idx = this.hostsToListIndexMap.remove(host);
        long[] newResponseTimes = new long[this.responseTimes.length - 1];
        int newIdx = 0;
        for (Iterator<String> i = this.hostList.iterator(); i.hasNext(); newIdx++) {
          String copyHost = i.next();
          if (idx != null && idx < this.responseTimes.length) {
            newResponseTimes[newIdx] = this.responseTimes[idx];
            this.hostsToListIndexMap.put(copyHost, newIdx);
          }
        }
        this.responseTimes = newResponseTimes;
      }
    }
  }
Exemple #8
0
 public synchronized void truncate(long len) throws SQLException {
   checkClosed();
   if (len < 0L) {
     throw SQLError.createSQLException(
         "\"len\" argument can not be < 1.", "S1009", this.exceptionInterceptor);
   }
   if (len > this.binaryData.length) {
     throw SQLError.createSQLException(
         "\"len\" argument can not be larger than the BLOB's length.",
         "S1009",
         this.exceptionInterceptor);
   }
   byte[] newData = new byte[(int) len];
   System.arraycopy(getBinaryData(), 0, newData, 0, (int) len);
   this.binaryData = newData;
 }
  /**
   * Creates a proxy for java.sql.Connection that routes requests between the given list of
   * host:port and uses the given properties when creating connections.
   *
   * @param hosts
   * @param props
   * @throws SQLException
   */
  LoadBalancingConnectionProxy(List hosts, Properties props) throws SQLException {
    this.hostList = hosts;

    int numHosts = this.hostList.size();

    this.liveConnections = new HashMap(numHosts);
    this.connectionsToHostsMap = new HashMap(numHosts);
    this.responseTimes = new long[numHosts];
    this.hostsToListIndexMap = new HashMap(numHosts);

    for (int i = 0; i < numHosts; i++) {
      this.hostsToListIndexMap.put(this.hostList.get(i), new Integer(i));
    }

    this.localProps = (Properties) props.clone();
    this.localProps.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    this.localProps.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);
    this.localProps.setProperty("useLocalSessionState", "true");

    String strategy = this.localProps.getProperty("loadBalanceStrategy", "random");

    if ("random".equals(strategy)) {
      this.balancer = new RandomBalanceStrategy();
    } else if ("bestResponseTime".equals(strategy)) {
      this.balancer = new BestResponseTimeBalanceStrategy();
    } else {
      throw SQLError.createSQLException(
          Messages.getString("InvalidLoadBalanceStrategy", new Object[] {strategy}),
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
    }

    pickNewConnection();
  }
 public <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
     try {
         // This works for classes that aren't actually wrapping anything
         return iface.cast(this);
     } catch (ClassCastException cce) {
         throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
     }
 }
 private synchronized void checkWorkingWithResult() throws SQLException {
   if (this.workingWithResult) {
     throw SQLError.createSQLException(
         "Can't perform requested operation after getResult() has been called to write XML data",
         SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
         this.exceptionInterceptor);
   }
 }
Exemple #12
0
  private void nextRecord() throws SQLException {

    try {
      if (!this.noMoreRows) {
        this.nextRow =
            this.isInterrupted
                ? null
                : this.io.nextRow(
                    this.metadata,
                    this.columnCount,
                    this.isBinaryEncoded,
                    java.sql.ResultSet.CONCUR_READ_ONLY,
                    true,
                    this.useBufferRowExplicit,
                    true,
                    null);

        if (this.nextRow == null) {
          this.noMoreRows = true;
          this.isAfterEnd = true;
          this.moreResultsExisted = this.io.tackOnMoreStreamingResults(this.owner);

          if (this.index == -1) {
            this.wasEmpty = true;
          }
        }
      } else {
        this.isAfterEnd = true;
      }
    } catch (SQLException sqlEx) {
      if (sqlEx instanceof StreamingNotifiable) {
        ((StreamingNotifiable) sqlEx).setWasStreamingResults();
      } else if (sqlEx instanceof MySQLQueryInterruptedException) {
        this.isInterrupted = true;
      }

      // don't wrap SQLExceptions
      throw sqlEx;
    } catch (Exception ex) {
      String exceptionType = ex.getClass().getName();
      String exceptionMessage = ex.getMessage();

      exceptionMessage += Messages.getString("RowDataDynamic.7");
      exceptionMessage += Util.stackTraceToString(ex);

      SQLException sqlEx =
          SQLError.createSQLException(
              Messages.getString("RowDataDynamic.8")
                  + exceptionType
                  + Messages.getString("RowDataDynamic.9")
                  + exceptionMessage,
              SQLError.SQL_STATE_GENERAL_ERROR,
              this.exceptionInterceptor);
      sqlEx.initCause(ex);

      throw sqlEx;
    }
  }
  /**
   * Returns the field instance for the given column index
   *
   * @param columnIndex the column number to retrieve a field instance for
   * @return the field instance for the given column index
   * @throws SQLException if an error occurs
   */
  protected Field getField(int columnIndex) throws SQLException {
    if ((columnIndex < 1) || (columnIndex > this.fields.length)) {
      throw SQLError.createSQLException(
          Messages.getString("ResultSetMetaData.46"), // $NON-NLS-1$
          SQLError.SQL_STATE_INVALID_COLUMN_NUMBER);
    }

    return this.fields[columnIndex - 1];
  }
Exemple #14
0
  MysqlSavepoint(String name, ExceptionInterceptor exceptionInterceptor) throws SQLException {
    if ((name == null) || (name.length() == 0)) {
      throw SQLError.createSQLException(
          "Savepoint name can not be NULL or empty", "S1009", exceptionInterceptor);
    }
    this.savepointName = name;

    this.exceptionInterceptor = exceptionInterceptor;
  }
Exemple #15
0
 public synchronized InputStream getBinaryStream(long pos, long length) throws SQLException {
   checkClosed();
   if (pos < 1L) {
     throw SQLError.createSQLException(
         "\"pos\" argument can not be < 1.", "S1009", this.exceptionInterceptor);
   }
   pos -= 1L;
   if (pos > this.binaryData.length) {
     throw SQLError.createSQLException(
         "\"pos\" argument can not be larger than the BLOB's length.",
         "S1009",
         this.exceptionInterceptor);
   }
   if (pos + length > this.binaryData.length) {
     throw SQLError.createSQLException(
         "\"pos\" + \"length\" arguments can not be larger than the BLOB's length.",
         "S1009",
         this.exceptionInterceptor);
   }
   return new ByteArrayInputStream(getBinaryData(), (int) pos, (int) length);
 }
Exemple #16
0
  /** Read string[$len] */
  final String readString(
      String encoding, ExceptionInterceptor exceptionInterceptor, int expectedLength)
      throws SQLException {
    if (this.position + expectedLength > getBufLength()) {
      throw SQLError.createSQLException(
          Messages.getString("ByteArrayBuffer.2"),
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          exceptionInterceptor);
    }

    try {
      return StringUtils.toString(this.byteBuffer, this.position, expectedLength, encoding);
    } catch (UnsupportedEncodingException uEE) {
      throw SQLError.createSQLException(
          Messages.getString("ByteArrayBuffer.1") + encoding + "'",
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          exceptionInterceptor);
    } finally {
      this.position += expectedLength; // update cursor
    }
  }
  /**
   * Get a description of a table's primary key columns. They are ordered by COLUMN_NAME.
   *
   * <p>Each column description has the following columns:
   *
   * <OL>
   *   <li><B>TABLE_CAT</B> String => table catalog (may be null)
   *   <li><B>TABLE_SCHEM</B> String => table schema (may be null)
   *   <li><B>TABLE_NAME</B> String => table name
   *   <li><B>COLUMN_NAME</B> String => column name
   *   <li><B>KEY_SEQ</B> short => sequence number within primary key
   *   <li><B>PK_NAME</B> String => primary key name (may be null)
   * </ol>
   *
   * @param catalog a catalog name; "" retrieves those without a catalog
   * @param schema a schema name pattern; "" retrieves those without a schema
   * @param table a table name
   * @return ResultSet each row is a primary key column description
   * @throws SQLException DOCUMENT ME!
   */
  public java.sql.ResultSet getPrimaryKeys(String catalog, String schema, String table)
      throws SQLException {

    if (catalog == null) {
      if (this.conn.getNullCatalogMeansCurrent()) {
        catalog = this.database;
      }
    }

    if (table == null) {
      throw SQLError.createSQLException(
          "Table not specified.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
    }

    String sql =
        "SELECT TABLE_SCHEMA AS TABLE_CAT, NULL AS TABLE_SCHEM, TABLE_NAME, "
            + "COLUMN_NAME, SEQ_IN_INDEX AS KEY_SEQ, 'PRIMARY' AS PK_NAME FROM INFORMATION_SCHEMA.STATISTICS "
            + "WHERE TABLE_SCHEMA LIKE ? AND TABLE_NAME LIKE ? AND "
            + "INDEX_NAME='PRIMARY' ORDER BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX";

    PreparedStatement pStmt = null;

    try {
      pStmt = prepareMetaDataSafeStatement(sql);

      if (catalog != null) {
        pStmt.setString(1, catalog);
      } else {
        pStmt.setString(1, "%");
      }

      pStmt.setString(2, table);

      ResultSet rs = executeMetadataQuery(pStmt);
      ((com.mysql.jdbc.ResultSet) rs)
          .redefineFieldsForDBMD(
              new Field[] {
                new Field("", "TABLE_CAT", Types.CHAR, 255),
                new Field("", "TABLE_SCHEM", Types.CHAR, 0),
                new Field("", "TABLE_NAME", Types.CHAR, 255),
                new Field("", "COLUMN_NAME", Types.CHAR, 32),
                new Field("", "KEY_SEQ", Types.SMALLINT, 5),
                new Field("", "PK_NAME", Types.CHAR, 32)
              });

      return rs;
    } finally {
      if (pStmt != null) {
        pStmt.close();
      }
    }
  }
Exemple #18
0
 public synchronized OutputStream setBinaryStream(long indexToWriteAt) throws SQLException {
   checkClosed();
   if (indexToWriteAt < 1L) {
     throw SQLError.createSQLException(
         Messages.getString("Blob.0"), "S1009", this.exceptionInterceptor);
   }
   WatchableOutputStream bytesOut = new WatchableOutputStream();
   bytesOut.setWatcher(this);
   if (indexToWriteAt > 0L) {
     bytesOut.write(this.binaryData, 0, (int) (indexToWriteAt - 1L));
   }
   return bytesOut;
 }
  public CommunicationsException(
      MySQLConnection conn,
      long lastPacketSentTimeMs,
      long lastPacketReceivedTimeMs,
      Exception underlyingException) {
    this.exceptionMessage =
        SQLError.createLinkFailureMessageBasedOnHeuristics(
            conn, lastPacketSentTimeMs, lastPacketReceivedTimeMs, underlyingException);

    if (underlyingException != null) {
      initCause(underlyingException);
    }
  }
Exemple #20
0
  public synchronized byte[] getBytes(long pos, int length) throws SQLException {
    checkClosed();
    if (pos < 1L) {
      throw SQLError.createSQLException(
          Messages.getString("Blob.2"), "S1009", this.exceptionInterceptor);
    }
    pos -= 1L;
    if (pos > this.binaryData.length) {
      throw SQLError.createSQLException(
          "\"pos\" argument can not be larger than the BLOB's length.",
          "S1009",
          this.exceptionInterceptor);
    }
    if (pos + length > this.binaryData.length) {
      throw SQLError.createSQLException(
          "\"pos\" + \"length\" arguments can not be larger than the BLOB's length.",
          "S1009",
          this.exceptionInterceptor);
    }
    byte[] newData = new byte[length];
    System.arraycopy(getBinaryData(), (int) pos, newData, 0, length);

    return newData;
  }
Exemple #21
0
  public Reader getReader(int columnIndex) throws SQLException {
    InputStream stream = getBinaryInputStream(columnIndex);

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

    try {
      return new InputStreamReader(stream, this.metadata[columnIndex].getCharacterSet());
    } catch (UnsupportedEncodingException e) {
      SQLException sqlEx = SQLError.createSQLException("", this.exceptionInterceptor);

      sqlEx.initCause(e);

      throw sqlEx;
    }
  }
Exemple #22
0
  /**
   * @param columnIndex
   * @param bits
   * @param offset
   * @param length
   * @param conn
   * @param rs
   * @param cal
   * @return
   * @throws SQLException
   */
  protected java.sql.Date getNativeDate(
      int columnIndex,
      byte[] bits,
      int offset,
      int length,
      MySQLConnection conn,
      ResultSetImpl rs,
      Calendar cal)
      throws SQLException {

    int year = 0;
    int month = 0;
    int day = 0;

    if (length != 0) {
      year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8);

      month = bits[offset + 2];
      day = bits[offset + 3];
    }

    if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) {
      if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(
          conn.getZeroDateTimeBehavior())) {
        return null;
      } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(
          conn.getZeroDateTimeBehavior())) {
        throw SQLError.createSQLException(
            "Value '0000-00-00' can not be represented as java.sql.Date",
            SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
            this.exceptionInterceptor);
      }

      year = 1;
      month = 1;
      day = 1;
    }

    if (!rs.useLegacyDatetimeCode) {
      return TimeUtil.fastDateCreate(year, month, day, cal);
    }

    return rs.fastDateCreate(
        cal == null ? rs.getCalendarInstanceForSessionOrNew() : cal, year, month, day);
  }
  protected java.sql.Connection connectReplicationConnection(String url, Properties info)
      throws SQLException {
    Properties parsedProps = parseURL(url, info);

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

    Properties masterProps = (Properties) parsedProps.clone();
    Properties slavesProps = (Properties) parsedProps.clone();

    // Marker used for further testing later on, also when
    // debugging
    slavesProps.setProperty("com.mysql.jdbc.ReplicationConnection.isSlave", "true");

    int numHosts = Integer.parseInt(parsedProps.getProperty(NUM_HOSTS_PROPERTY_KEY));

    if (numHosts < 2) {
      throw SQLError.createSQLException(
          "Must specify at least one slave host to connect to for master/slave replication load-balancing functionality",
          SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
          null);
    }

    for (int i = 1; i < numHosts; i++) {
      int index = i + 1;

      masterProps.remove(HOST_PROPERTY_KEY + "." + index);
      masterProps.remove(PORT_PROPERTY_KEY + "." + index);

      slavesProps.setProperty(
          HOST_PROPERTY_KEY + "." + i, parsedProps.getProperty(HOST_PROPERTY_KEY + "." + index));
      slavesProps.setProperty(
          PORT_PROPERTY_KEY + "." + i, parsedProps.getProperty(PORT_PROPERTY_KEY + "." + index));
    }

    masterProps.setProperty(NUM_HOSTS_PROPERTY_KEY, "1");
    slavesProps.remove(HOST_PROPERTY_KEY + "." + numHosts);
    slavesProps.remove(PORT_PROPERTY_KEY + "." + numHosts);
    slavesProps.setProperty(NUM_HOSTS_PROPERTY_KEY, String.valueOf(numHosts - 1));
    slavesProps.setProperty(HOST_PROPERTY_KEY, slavesProps.getProperty(HOST_PROPERTY_KEY + ".1"));
    slavesProps.setProperty(PORT_PROPERTY_KEY, slavesProps.getProperty(PORT_PROPERTY_KEY + ".1"));

    return new ReplicationConnection(masterProps, slavesProps);
  }
  protected String domSourceToString() throws SQLException {
    try {
      DOMSource source = new DOMSource(this.asDOMResult.getNode());
      Transformer identity = TransformerFactory.newInstance().newTransformer();
      StringWriter stringOut = new StringWriter();
      Result result = new StreamResult(stringOut);
      identity.transform(source, result);

      return stringOut.toString();
    } catch (Throwable t) {
      SQLException sqlEx =
          SQLError.createSQLException(
              t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
      sqlEx.initCause(t);

      throw sqlEx;
    }
  }
  protected String readerToString(Reader reader) throws SQLException {
    StringBuffer buf = new StringBuffer();

    int charsRead = 0;

    char[] charBuf = new char[512];

    try {
      while ((charsRead = reader.read(charBuf)) != -1) {
        buf.append(charBuf, 0, charsRead);
      }
    } catch (IOException ioEx) {
      SQLException sqlEx =
          SQLError.createSQLException(
              ioEx.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
      sqlEx.initCause(ioEx);

      throw sqlEx;
    }

    return buf.toString();
  }
Exemple #26
0
  /**
   * Read string[NUL]
   *
   * @param encoding
   * @param exceptionInterceptor
   * @throws SQLException
   */
  final String readString(String encoding, ExceptionInterceptor exceptionInterceptor)
      throws SQLException {
    int i = this.position;
    int len = 0;
    int maxLen = getBufLength();

    while ((i < maxLen) && (this.byteBuffer[i] != 0)) {
      len++;
      i++;
    }

    try {
      return StringUtils.toString(this.byteBuffer, this.position, len, encoding);
    } catch (UnsupportedEncodingException uEE) {
      throw SQLError.createSQLException(
          Messages.getString("ByteArrayBuffer.1") + encoding + "'",
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          exceptionInterceptor);
    } finally {
      this.position += (len + 1); // update cursor
    }
  }
Exemple #27
0
  public synchronized int setBytes(long writeAt, byte[] bytes, int offset, int length)
      throws SQLException {
    checkClosed();

    OutputStream bytesOut = setBinaryStream(writeAt);
    try {
      bytesOut.write(bytes, offset, length);
    } catch (IOException ioEx) {
      SQLException sqlEx =
          SQLError.createSQLException(
              Messages.getString("Blob.1"), "S1000", this.exceptionInterceptor);

      sqlEx.initCause(ioEx);

      throw sqlEx;
    } finally {
      try {
        bytesOut.close();
      } catch (IOException doNothing) {
      }
    }
    return length;
  }
  /**
   * Returns a Source for reading the XML value designated by this SQLXML instance. Sources are used
   * as inputs to XML parsers and XSLT transformers.
   *
   * <p>Sources for XML parsers will have namespace processing on by default. The systemID of the
   * Source is implementation dependent.
   *
   * <p>The SQL XML object becomes not readable when this method is called and may also become not
   * writable depending on implementation.
   *
   * <p>Note that SAX is a callback architecture, so a returned SAXSource should then be set with a
   * content handler that will receive the SAX events from parsing. The content handler will receive
   * callbacks based on the contents of the XML.
   *
   * <pre>
   * SAXSource saxSource = sqlxml.getSource(SAXSource.class);
   * XMLReader xmlReader = saxSource.getXMLReader();
   * xmlReader.setContentHandler(myHandler);
   * xmlReader.parse(saxSource.getInputSource());
   * </pre>
   *
   * @param sourceClass The class of the source, or null. If the class is null, a vendor specifc
   *     Source implementation will be returned. The following classes are supported at a minimum:
   *     <p>(MySQL returns a SAXSource if sourceClass == null)
   *     <pre>
   *    javax.xml.transform.dom.DOMSource - returns a DOMSource
   *    javax.xml.transform.sax.SAXSource - returns a SAXSource
   *    javax.xml.transform.stax.StAXSource - returns a StAXSource
   *    javax.xml.transform.stream.StreamSource - returns a StreamSource
   * </pre>
   *
   * @return a Source for reading the XML value.
   * @throws SQLException if there is an error processing the XML value or if this feature is not
   *     supported. The getCause() method of the exception may provide a more detailed exception,
   *     for example, if an XML parser exception occurs. An exception is thrown if the state is not
   *     readable.
   * @exception SQLFeatureNotSupportedException if the JDBC driver does not support this method
   * @since 1.6
   */
  public synchronized Source getSource(Class clazz) throws SQLException {
    checkClosed();
    checkWorkingWithResult();

    // Note that we try and use streams here wherever possible
    // for the day that the server actually supports streaming
    // from server -> client (futureproofing)

    if (clazz == null || clazz.equals(SAXSource.class)) {

      InputSource inputSource = null;

      if (this.fromResultSet) {
        inputSource =
            new InputSource(this.owningResultSet.getCharacterStream(this.columnIndexOfXml));
      } else {
        inputSource = new InputSource(new StringReader(this.stringRep));
      }

      return new SAXSource(inputSource);
    } else if (clazz.equals(DOMSource.class)) {
      try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        InputSource inputSource = null;

        if (this.fromResultSet) {
          inputSource =
              new InputSource(this.owningResultSet.getCharacterStream(this.columnIndexOfXml));
        } else {
          inputSource = new InputSource(new StringReader(this.stringRep));
        }

        return new DOMSource(builder.parse(inputSource));
      } catch (Throwable t) {
        SQLException sqlEx =
            SQLError.createSQLException(
                t.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(t);

        throw sqlEx;
      }

    } else if (clazz.equals(StreamSource.class)) {
      Reader reader = null;

      if (this.fromResultSet) {
        reader = this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
      } else {
        reader = new StringReader(this.stringRep);
      }

      return new StreamSource(reader);
    } else if (clazz.equals(StAXSource.class)) {
      try {
        Reader reader = null;

        if (this.fromResultSet) {
          reader = this.owningResultSet.getCharacterStream(this.columnIndexOfXml);
        } else {
          reader = new StringReader(this.stringRep);
        }

        return new StAXSource(this.inputFactory.createXMLStreamReader(reader));
      } catch (XMLStreamException ex) {
        SQLException sqlEx =
            SQLError.createSQLException(
                ex.getMessage(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
        sqlEx.initCause(ex);

        throw sqlEx;
      }
    } else {
      throw SQLError.createSQLException(
          "XML Source of type \"" + clazz.toString() + "\" Not supported.",
          SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
          this.exceptionInterceptor);
    }
  }
 private synchronized void checkClosed() throws SQLException {
   if (this.isClosed) {
     throw SQLError.createSQLException(
         "SQLXMLInstance has been free()d", this.exceptionInterceptor);
   }
 }
  public Properties parseURL(String url, Properties defaults) throws java.sql.SQLException {
    Properties urlProps = (defaults != null) ? new Properties(defaults) : new Properties();

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

    if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX)
        && !StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { // $NON-NLS-1$

      return null;
    }

    int beginningOfSlashes = url.indexOf("//");

    if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) {

      urlProps.setProperty(
          "socketFactory", "com.mysql.management.driverlaunched.ServerLauncherSocketFactory");
    }

    /*
     * Parse parameters after the ? in the URL and remove them from the
     * original URL.
     */
    int index = url.indexOf("?"); // $NON-NLS-1$

    if (index != -1) {
      String paramString = url.substring(index + 1, url.length());
      url = url.substring(0, index);

      StringTokenizer queryParams = new StringTokenizer(paramString, "&"); // $NON-NLS-1$

      while (queryParams.hasMoreTokens()) {
        String parameterValuePair = queryParams.nextToken();

        int indexOfEquals = StringUtils.indexOfIgnoreCase(0, parameterValuePair, "=");

        String parameter = null;
        String value = null;

        if (indexOfEquals != -1) {
          parameter = parameterValuePair.substring(0, indexOfEquals);

          if (indexOfEquals + 1 < parameterValuePair.length()) {
            value = parameterValuePair.substring(indexOfEquals + 1);
          }
        }

        if ((value != null && value.length() > 0)
            && (parameter != null && parameter.length() > 0)) {
          try {
            urlProps.put(parameter, URLDecoder.decode(value, "UTF-8"));
          } catch (UnsupportedEncodingException badEncoding) {
            // punt
            urlProps.put(parameter, URLDecoder.decode(value));
          } catch (NoSuchMethodError nsme) {
            // punt again
            urlProps.put(parameter, URLDecoder.decode(value));
          }
        }
      }
    }

    url = url.substring(beginningOfSlashes + 2);

    String hostStuff = null;

    int slashIndex =
        StringUtils.indexOfIgnoreCaseRespectMarker(
            0, url, "/", ALLOWED_QUOTES, ALLOWED_QUOTES, true); // $NON-NLS-1$

    if (slashIndex != -1) {
      hostStuff = url.substring(0, slashIndex);

      if ((slashIndex + 1) < url.length()) {
        urlProps.put(
            DBNAME_PROPERTY_KEY, //$NON-NLS-1$
            url.substring((slashIndex + 1), url.length()));
      }
    } else {
      hostStuff = url;
    }

    int numHosts = 0;

    if ((hostStuff != null) && (hostStuff.trim().length() > 0)) {
      List<String> hosts = StringUtils.split(hostStuff, ",", ALLOWED_QUOTES, ALLOWED_QUOTES, false);

      for (String hostAndPort : hosts) {
        numHosts++;

        String[] hostPortPair = parseHostPortPair(hostAndPort);

        if (hostPortPair[HOST_NAME_INDEX] != null
            && hostPortPair[HOST_NAME_INDEX].trim().length() > 0) {
          urlProps.setProperty(HOST_PROPERTY_KEY + "." + numHosts, hostPortPair[HOST_NAME_INDEX]);
        } else {
          urlProps.setProperty(HOST_PROPERTY_KEY + "." + numHosts, "localhost");
        }

        if (hostPortPair[PORT_NUMBER_INDEX] != null) {
          urlProps.setProperty(PORT_PROPERTY_KEY + "." + numHosts, hostPortPair[PORT_NUMBER_INDEX]);
        } else {
          urlProps.setProperty(PORT_PROPERTY_KEY + "." + numHosts, "3306");
        }
      }
    } else {
      numHosts = 1;
      urlProps.setProperty(HOST_PROPERTY_KEY + ".1", "localhost");
      urlProps.setProperty(PORT_PROPERTY_KEY + ".1", "3306");
    }

    urlProps.setProperty(NUM_HOSTS_PROPERTY_KEY, String.valueOf(numHosts));
    urlProps.setProperty(HOST_PROPERTY_KEY, urlProps.getProperty(HOST_PROPERTY_KEY + ".1"));
    urlProps.setProperty(PORT_PROPERTY_KEY, urlProps.getProperty(PORT_PROPERTY_KEY + ".1"));

    String propertiesTransformClassName = urlProps.getProperty(PROPERTIES_TRANSFORM_KEY);

    if (propertiesTransformClassName != null) {
      try {
        ConnectionPropertiesTransform propTransformer =
            (ConnectionPropertiesTransform)
                Class.forName(propertiesTransformClassName).newInstance();

        urlProps = propTransformer.transformProperties(urlProps);
      } catch (InstantiationException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
            null);
      } catch (IllegalAccessException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
            null);
      } catch (ClassNotFoundException e) {
        throw SQLError.createSQLException(
            "Unable to create properties transform instance '"
                + propertiesTransformClassName
                + "' due to underlying exception: "
                + e.toString(),
            SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
            null);
      }
    }

    if (Util.isColdFusion()
        && urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) {
      String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);

      StringBuffer newConfigs = new StringBuffer();

      if (configs != null) {
        newConfigs.append(configs);
        newConfigs.append(",");
      }

      newConfigs.append("coldFusion");

      urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString());
    }

    // If we use a config, it actually should get overridden by anything in
    // the URL or passed-in properties

    String configNames = null;

    if (defaults != null) {
      configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames == null) {
      configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY);
    }

    if (configNames != null) {
      List splitNames = StringUtils.split(configNames, ",", true);

      Properties configProps = new Properties();

      Iterator namesIter = splitNames.iterator();

      while (namesIter.hasNext()) {
        String configName = (String) namesIter.next();

        try {
          InputStream configAsStream =
              getClass().getResourceAsStream("configs/" + configName + ".properties");

          if (configAsStream == null) {
            throw SQLError.createSQLException(
                "Can't find configuration template named '" + configName + "'",
                SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
                null);
          }
          configProps.load(configAsStream);
        } catch (IOException ioEx) {
          SQLException sqlEx =
              SQLError.createSQLException(
                  "Unable to load configuration template '"
                      + configName
                      + "' due to underlying IOException: "
                      + ioEx,
                  SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE,
                  null);
          sqlEx.initCause(ioEx);

          throw sqlEx;
        }
      }

      Iterator propsIter = urlProps.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        String property = urlProps.getProperty(key);
        configProps.setProperty(key, property);
      }

      urlProps = configProps;
    }

    // Properties passed in should override ones in URL

    if (defaults != null) {
      Iterator propsIter = defaults.keySet().iterator();

      while (propsIter.hasNext()) {
        String key = propsIter.next().toString();
        if (!key.equals(NUM_HOSTS_PROPERTY_KEY)) {
          String property = defaults.getProperty(key);
          urlProps.setProperty(key, property);
        }
      }
    }

    return urlProps;
  }