Exemplo n.º 1
1
 /**
  * Executes an SQL statement on the database in a separate thread. A certain number of worker
  * threads controlled by the "parallel" property will operate simultaneously.
  *
  * @param sql an SQL string.
  * @throws SQLException if an error has been reported by a previous operation - however, this does
  *     not cancel the current operation.
  */
 public void executeSqlInParallel(String sql) throws SQLException {
   SqlJob job = new SqlJob(sql);
   synchronized (this) {
     pending.add(job);
   }
   boolean notDone = true;
   while (notDone) {
     try {
       queue.put(job);
       notDone = false;
     } catch (InterruptedException e) {
       // Not done
     }
   }
   synchronized (this) {
     if (workers.size() < parallel) {
       Worker worker = new Worker(threadNo);
       Thread thread = new Thread(worker);
       thread.setDaemon(true);
       thread.setName("Database background thread " + threadNo);
       threadNo++;
       workers.add(worker);
       thread.start();
     }
     if (reportedException != null) {
       SQLException re = new SQLException("Error while executing SQL");
       re.initCause(reportedException);
       reportedException = null;
       throw re;
     }
   }
 }
Exemplo n.º 2
0
 /** {@inheritDoc} */
 @Override
 public void nullSafeSet(
     final PreparedStatement statement,
     final Object value,
     final int index,
     final SessionImplementor session)
     throws SQLException {
   if (value == null) {
     statement.setNull(index, sqlTypes()[0]);
   } else {
     // Cf io.vertigo.dynamo.impl.database.vendor.core.SQLMappingImpl
     try {
       final DataStream dataStream = (DataStream) value;
       statement.setBinaryStream(
           index,
           dataStream.createInputStream(),
           (int)
               dataStream
                   .getLength()); // attention le setBinaryStream avec une longueur de fichier en
                                  // long N'EST PAS implémentée dans de nombreux drivers !!
     } catch (final IOException e) {
       final SQLException sqlException = new SQLException("Erreur d'ecriture du flux");
       sqlException.initCause(e);
       throw sqlException;
     }
   }
 }
  public void logBatchUpdateExceptions(Throwable t) {
    while (!(t instanceof SQLException)) {
      t = t.getCause();
      if (t == null) {
        return;
      }
    }

    SQLException sqle = (SQLException) t;

    // If the SQLException is the root chain the results of getNextException as initCauses
    if (sqle.getCause() == null) {
      SQLException nextException;
      while ((nextException = sqle.getNextException()) != null) {
        sqle.initCause(nextException);
        sqle = nextException;
      }
    }
    // The SQLException already has a cause so log the results of all getNextException calls
    else {
      while ((sqle = sqle.getNextException()) != null) {
        this.logger.error("Logging getNextException for root SQLException: " + t, sqle);
      }
    }
  }
Exemplo n.º 4
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;
    }
  }
Exemplo n.º 5
0
  /**
   * This method will send an close command, which does not return any rowsets, to the ODBC server.
   *
   * @retrun A CloseReply class representing the reply from the ODBC server is returned
   * @exception A SQLException is thrown
   */
  CloseReply Close() throws SQLException {

    try {
      getInputOutput().setTimeout(m_ic.t4props_.getNetworkTimeout());

      LogicalByteArray wbuffer =
          CloseMessage.marshal(m_dialogueId, m_stmtLabel, SQL_CLOSE, this.m_ic);

      LogicalByteArray rbuffer = getReadBuffer(TRANSPORT.SRVR_API_SQLFREESTMT, wbuffer);

      CloseReply cr = new CloseReply(rbuffer, m_ncsAddress.getIPorName(), m_ic);

      return cr;
    } // end try
    catch (SQLException se) {
      throw se;
    } catch (CharacterCodingException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_,
              m_locale,
              "translation_of_parameter_failed",
              "CloseMessage",
              e.getMessage());
      se.initCause(e);
      throw se;
    } catch (UnsupportedCharsetException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "unsupported_encoding", e.getCharsetName());
      se.initCause(e);
      throw se;
    } catch (Exception e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "close_message_error", e.getMessage());

      se.initCause(e);
      throw se;
    } // end catch
  } // end Close
Exemplo n.º 6
0
  /**
   * クラスタリング対応のメソッド実行処理。
   *
   * @param methodName
   * @param args
   * @return
   * @throws SQLException
   */
  private Object clusterCall(
      String methodName, Object[] args, Class<?>[] parameterTypes, boolean saveMethod)
      throws SQLException {
    Object result = null;
    CalledMethod calledMethod = new CalledMethod(methodName, args, parameterTypes);

    logger.debug(calledMethod.toString());

    try {
      result = calledMethod.invoke(st);
    } catch (Exception e) {
      logger.warn(MSG_WARN_SWITCH_DB, e);
      // try { st.close(); } catch (SQLException se) {}
      con.notifyError(this); // エラーを通知。ここでstは新しいものになっているはず。
      try {
        // 再度実行。ここでもさらにエラーがでるならSQLExceptionにラップする。
        result = calledMethod.invoke(st);
      } catch (InvocationTargetException e2) {
        // 例外がSQLExceptionならそのままthrow
        Throwable t = e2.getTargetException();
        if (t instanceof SQLException) {
          throw (SQLException) t;
        }
        // それ以外ならwrapしてthrow
        SQLException sqle = new SQLException();
        sqle.initCause(e2.getTargetException());
        throw sqle;
      } catch (Exception e2) {
        SQLException sqle = new SQLException();
        sqle.initCause(e2);
        throw sqle;
      }
    }
    if (saveMethod) {
      methodList.add(calledMethod);
    }

    return result;
  }
Exemplo n.º 7
0
  /**
   * 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);
    }
  }
Exemplo n.º 8
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;
    }
  }
Exemplo n.º 9
0
 /**
  * Blocks until all the current pending jobs are finished. This will not block new jobs from
  * arriving, and those new jobs do not need to be finished for this method to return.
  *
  * @throws SQLException if an error has been reported by a previous operation
  */
 public void waitForCurrentJobs() throws SQLException {
   Waiter waiter;
   synchronized (this) {
     waiter = new Waiter(pending);
     waiters.add(waiter);
   }
   waiter.waitUntilFinished();
   synchronized (this) {
     waiters.remove(waiter);
     if (reportedException != null) {
       SQLException re = new SQLException("Error while executing SQL");
       re.initCause(reportedException);
       reportedException = null;
       throw re;
     }
   }
 }
Exemplo n.º 10
0
  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;
    }
  }
Exemplo n.º 11
0
  /**
   * 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;
    }

    if (!"1".equals(props.getProperty(NUM_HOSTS_PROPERTY_KEY))) {
      return connectFailover(url, info);
    }

    try {
      Connection newConn =
          com.mysql.jdbc.ConnectionImpl.getInstance(
              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) {
      SQLException sqlEx =
          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,
              null);

      sqlEx.initCause(ex);

      throw sqlEx;
    }
  }
Exemplo n.º 12
0
  public static SQLException toSQLException(String msg, String sqlState, Throwable t) {
    if (t instanceof SQLException) {
      if (Debug.DEBUG && Debug.TRACE == Debug.TRACE_MAX && logger.isLoggable(MLevel.FINER)) {
        SQLException s = (SQLException) t;
        StringBuffer tmp = new StringBuffer(255);
        tmp.append("Attempted to convert SQLException to SQLException. Leaving it alone.");
        tmp.append(" [SQLState: ");
        tmp.append(s.getSQLState());
        tmp.append("; errorCode: ");
        tmp.append(s.getErrorCode());
        tmp.append(']');
        if (msg != null) tmp.append(" Ignoring suggested message: '" + msg + "'.");
        logger.log(MLevel.FINER, tmp.toString(), t);

        SQLException s2 = s;
        while ((s2 = s2.getNextException()) != null)
          logger.log(MLevel.FINER, "Nested SQLException or SQLWarning: ", s2);
      }
      return (SQLException) t;
    } else {
      if (Debug.DEBUG) {
        // t.printStackTrace();
        if (logger.isLoggable(MLevel.FINE))
          logger.log(MLevel.FINE, "Converting Throwable to SQLException...", t);
      }

      if (msg == null)
        msg = "An SQLException was provoked by the following failure: " + t.toString();
      if (VersionUtils.isAtLeastJavaVersion14()) {
        SQLException out = new SQLException(msg);
        out.initCause(t);
        return out;
      } else
        return new SQLException(
            msg
                + System.getProperty("line.separator")
                + "[Cause: "
                + ThrowableUtils.extractStackTrace(t)
                + ']',
            sqlState);
    }
  }
Exemplo n.º 13
0
  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();
  }
Exemplo n.º 14
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;
  }
  public HarmonySerialClob(Clob clob) throws SQLException {
    Reader characterStream;

    if (clob == null) {
      throw new IllegalArgumentException();
    }
    if ((characterStream = clob.getCharacterStream()) == null && clob.getAsciiStream() == null) {
      throw new IllegalArgumentException();
    }

    this.clob = clob;
    origLen = clob.length();
    len = origLen;
    buf = new char[(int) len];
    try {
      characterStream.read(buf);
    } catch (IOException e) {
      SQLException se = new SQLException("SerialClob: " + e.getMessage());

      se.initCause(e);
      throw se;
    }
  }
Exemplo n.º 16
0
  /**
   * Converts a clob to a string.
   *
   * @param clob the clob to convert.
   * @return the clob contents.
   * @throws SQLException if the CLOB cannot be processed. See <a
   *     href="http://www.opengroup.org/bookstore/catalog/c449.htm">SQL 2</a>.
   */
  @NotNull
  public String clobToString(@NotNull final Clob clob) throws SQLException {
    @NotNull final StringBuilder t_sbResult = new StringBuilder();

    @Nullable SQLException t_ExceptionToThrow = null;

    @NotNull final BufferedReader t_Reader = new BufferedReader(clob.getCharacterStream());

    try {
      String t_strLine = t_Reader.readLine();

      while (t_strLine != null) {
        t_sbResult.append(t_strLine);

        t_strLine = t_Reader.readLine();
      } // end of while  ()

    } catch (@NotNull final IOException ioException) {
      t_ExceptionToThrow =
          new SQLException(
              "cannot.read.clob", "22021"); // "Translation result not in target repertoire"

      t_ExceptionToThrow.initCause(ioException);
    } finally {
      try {
        t_Reader.close();
      } catch (@NotNull final IOException ioException) {
        LogFactory.getLog(QueryUtils.class).warn("Cannot close CLOB stream.", ioException);
      }
    }

    if (t_ExceptionToThrow != null) {
      throw t_ExceptionToThrow;
    }

    return t_sbResult.toString();
  }
  @Test
  public void testEndTransactionWhenSQLBatchUpdateExceptionThrown() throws Exception {
    SQLException sqlException2 = new SQLException("sqlexception2");
    sqlException2.setNextException(new SQLException("nextexception2"));

    SQLException sqlException1 = new SQLException("sqlexception1");
    sqlException1.initCause(sqlException2);
    sqlException1.setNextException(new SQLException("nextexception1"));

    // Assume the transaction is already created.
    when(context.get("hibtransaction")).thenReturn(transaction);
    doThrow(new HibernateException("exception1", sqlException1)).when(transaction).commit();

    try {
      store.endTransaction(context, true);
      fail("Should have thrown an exception here");
    } catch (HibernateException e) {
      assertEquals(
          "Failed to commit or rollback transaction. Root cause [\n"
              + "SQL next exception = [java.sql.SQLException: nextexception1]\n"
              + "SQL next exception = [java.sql.SQLException: nextexception2]]",
          e.getMessage());
    }
  }
Exemplo n.º 18
0
 /** Convenience method to allow a cause. Grrrr. */
 public static SQLException create(String message, Throwable cause) {
   SQLException sqlException = new SQLException(message);
   sqlException.initCause(cause);
   return sqlException;
 }
Exemplo n.º 19
0
  protected final java.sql.Date getDateFast(
      int columnIndex,
      byte[] dateAsBytes,
      int offset,
      int length,
      MySQLConnection conn,
      ResultSetImpl rs,
      Calendar targetCalendar)
      throws SQLException {

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

    try {
      if (dateAsBytes == null) {
        return null;
      }

      boolean allZeroDate = true;

      boolean onlyTimePresent = false;

      for (int i = 0; i < length; i++) {
        if (dateAsBytes[offset + i] == ':') {
          onlyTimePresent = true;
          break;
        }
      }

      for (int i = 0; i < length; i++) {
        byte b = dateAsBytes[offset + i];

        if (b == ' ' || b == '-' || b == '/') {
          onlyTimePresent = false;
        }

        if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') {
          allZeroDate = false;

          break;
        }
      }

      if (!onlyTimePresent && allZeroDate) {

        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 '"
                  + StringUtils.toString(dateAsBytes)
                  + "' can not be represented as java.sql.Date",
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor);
        }

        // We're left with the case of 'round' to a date Java _can_
        // represent, which is '0001-01-01'.
        return rs.fastDateCreate(targetCalendar, 1, 1, 1);

      } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) {
        // Convert from TIMESTAMP
        switch (length) {
          case 29:
          case 21:
          case 19:
            { // java.sql.Timestamp format
              year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4);
              month = StringUtils.getInt(dateAsBytes, offset + 5, offset + 7);
              day = StringUtils.getInt(dateAsBytes, offset + 8, offset + 10);

              return rs.fastDateCreate(targetCalendar, year, month, day);
            }

          case 14:
          case 8:
            {
              year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4);
              month = StringUtils.getInt(dateAsBytes, offset + 4, offset + 6);
              day = StringUtils.getInt(dateAsBytes, offset + 6, offset + 8);

              return rs.fastDateCreate(targetCalendar, year, month, day);
            }

          case 12:
          case 10:
          case 6:
            {
              year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 2);

              if (year <= 69) {
                year = year + 100;
              }

              month = StringUtils.getInt(dateAsBytes, offset + 2, offset + 4);
              day = StringUtils.getInt(dateAsBytes, offset + 4, offset + 6);

              return rs.fastDateCreate(targetCalendar, year + 1900, month, day);
            }

          case 4:
            {
              year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4);

              if (year <= 69) {
                year = year + 100;
              }

              month = StringUtils.getInt(dateAsBytes, offset + 2, offset + 4);

              return rs.fastDateCreate(targetCalendar, year + 1900, month, 1);
            }

          case 2:
            {
              year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 2);

              if (year <= 69) {
                year = year + 100;
              }

              return rs.fastDateCreate(targetCalendar, year + 1900, 1, 1);
            }

          default:
            throw SQLError.createSQLException(
                Messages.getString(
                    "ResultSet.Bad_format_for_Date",
                    new Object[] {
                      StringUtils.toString(dateAsBytes), Integer.valueOf(columnIndex + 1)
                    }),
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                this.exceptionInterceptor); // $NON-NLS-1$
        } /* endswitch */
      } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) {

        if (length == 2 || length == 1) {
          year = StringUtils.getInt(dateAsBytes, offset, offset + length);

          if (year <= 69) {
            year = year + 100;
          }

          year += 1900;
        } else {
          year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4);
        }

        return rs.fastDateCreate(targetCalendar, year, 1, 1);
      } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIME) {
        return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return EPOCH
      } else {
        if (length < 10) {
          if (length == 8) {
            return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return
            // EPOCH for
            // TIME
          }

          throw SQLError.createSQLException(
              Messages.getString(
                  "ResultSet.Bad_format_for_Date",
                  new Object[] {
                    StringUtils.toString(dateAsBytes), Integer.valueOf(columnIndex + 1)
                  }),
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor); // $NON-NLS-1$
        }

        if (length != 18) {
          year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4);
          month = StringUtils.getInt(dateAsBytes, offset + 5, offset + 7);
          day = StringUtils.getInt(dateAsBytes, offset + 8, offset + 10);
        } else {
          // JDK-1.3 timestamp format, not real easy to parse
          // positionally :p
          StringTokenizer st =
              new StringTokenizer(
                  StringUtils.toString(dateAsBytes, offset, length, "ISO8859_1"), "- ");

          year = Integer.parseInt(st.nextToken());
          month = Integer.parseInt(st.nextToken());
          day = Integer.parseInt(st.nextToken());
        }
      }

      return rs.fastDateCreate(targetCalendar, year, month, day);
    } catch (SQLException sqlEx) {
      throw sqlEx; // don't re-wrap
    } catch (Exception e) {
      SQLException sqlEx =
          SQLError.createSQLException(
              Messages.getString(
                  "ResultSet.Bad_format_for_Date",
                  new Object[] {
                    StringUtils.toString(dateAsBytes), Integer.valueOf(columnIndex + 1)
                  }),
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor); // $NON-NLS-1$
      sqlEx.initCause(e);

      throw sqlEx;
    }
  }
Exemplo n.º 20
0
  protected Timestamp getTimestampFast(
      int columnIndex,
      byte[] timestampAsBytes,
      int offset,
      int length,
      Calendar targetCalendar,
      TimeZone tz,
      boolean rollForward,
      MySQLConnection conn,
      ResultSetImpl rs)
      throws SQLException {

    try {
      Calendar sessionCalendar =
          conn.getUseJDBCCompliantTimezoneShift()
              ? conn.getUtcCalendar()
              : rs.getCalendarInstanceForSessionOrNew();

      synchronized (sessionCalendar) {
        boolean allZeroTimestamp = true;

        boolean onlyTimePresent = false;

        for (int i = 0; i < length; i++) {
          if (timestampAsBytes[offset + i] == ':') {
            onlyTimePresent = true;
            break;
          }
        }

        for (int i = 0; i < length; i++) {
          byte b = timestampAsBytes[offset + i];

          if (b == ' ' || b == '-' || b == '/') {
            onlyTimePresent = false;
          }

          if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') {
            allZeroTimestamp = false;

            break;
          }
        }

        if (!onlyTimePresent && allZeroTimestamp) {

          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 '"
                    + StringUtils.toString(timestampAsBytes)
                    + "' can not be represented as java.sql.Timestamp",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                this.exceptionInterceptor);
          }

          if (!rs.useLegacyDatetimeCode) {
            return TimeUtil.fastTimestampCreate(tz, 1, 1, 1, 0, 0, 0, 0);
          }
          // We're left with the case of 'round' to a date Java _can_
          // represent, which is '0001-01-01'.
          return rs.fastTimestampCreate(null, 1, 1, 1, 0, 0, 0, 0);

        } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) {

          if (!rs.useLegacyDatetimeCode) {
            return TimeUtil.fastTimestampCreate(
                tz, StringUtils.getInt(timestampAsBytes, offset, 4), 1, 1, 0, 0, 0, 0);
          }

          return TimeUtil.changeTimezone(
              conn,
              sessionCalendar,
              targetCalendar,
              rs.fastTimestampCreate(
                  sessionCalendar,
                  StringUtils.getInt(timestampAsBytes, offset, 4),
                  1,
                  1,
                  0,
                  0,
                  0,
                  0),
              conn.getServerTimezoneTZ(),
              tz,
              rollForward);
        } else {
          if (timestampAsBytes[offset + length - 1] == '.') {
            length--;
          }

          // Convert from TIMESTAMP or DATE

          int year = 0;
          int month = 0;
          int day = 0;
          int hour = 0;
          int minutes = 0;
          int seconds = 0;
          int nanos = 0;

          switch (length) {
            case 29:
            case 26:
            case 25:
            case 24:
            case 23:
            case 22:
            case 21:
            case 20:
            case 19:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4);
                month = StringUtils.getInt(timestampAsBytes, offset + 5, offset + 7);
                day = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10);
                hour = StringUtils.getInt(timestampAsBytes, offset + 11, offset + 13);
                minutes = StringUtils.getInt(timestampAsBytes, offset + 14, offset + 16);
                seconds = StringUtils.getInt(timestampAsBytes, offset + 17, offset + 19);

                nanos = 0;

                if (length > 19) {
                  int decimalIndex = -1;

                  for (int i = 0; i < length; i++) {
                    if (timestampAsBytes[offset + i] == '.') {
                      decimalIndex = i;
                    }
                  }

                  if (decimalIndex != -1) {
                    if ((decimalIndex + 2) <= length) {
                      nanos =
                          StringUtils.getInt(
                              timestampAsBytes, offset + decimalIndex + 1, offset + length);

                      int numDigits = (length) - (decimalIndex + 1);

                      if (numDigits < 9) {
                        int factor = (int) (Math.pow(10, 9 - numDigits));
                        nanos = nanos * factor;
                      }
                    } else {
                      throw new IllegalArgumentException(); // re-thrown
                      // further
                      // down
                      // with
                      // a
                      // much better error message
                    }
                  }
                }

                break;
              }

            case 14:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4);
                month = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6);
                day = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8);
                hour = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10);
                minutes = StringUtils.getInt(timestampAsBytes, offset + 10, offset + 12);
                seconds = StringUtils.getInt(timestampAsBytes, offset + 12, offset + 14);

                break;
              }

            case 12:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);

                if (year <= 69) {
                  year = (year + 100);
                }

                year += 1900;

                month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4);
                day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6);
                hour = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8);
                minutes = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10);
                seconds = StringUtils.getInt(timestampAsBytes, offset + 10, offset + 12);

                break;
              }

            case 10:
              {
                boolean hasDash = false;

                for (int i = 0; i < length; i++) {
                  if (timestampAsBytes[offset + i] == '-') {
                    hasDash = true;
                    break;
                  }
                }

                if ((this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_DATE)
                    || hasDash) {
                  year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4);
                  month = StringUtils.getInt(timestampAsBytes, offset + 5, offset + 7);
                  day = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10);
                  hour = 0;
                  minutes = 0;
                } else {
                  year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);

                  if (year <= 69) {
                    year = (year + 100);
                  }

                  month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4);
                  day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6);
                  hour = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8);
                  minutes = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10);

                  year += 1900; // two-digit year
                }

                break;
              }

            case 8:
              {
                boolean hasColon = false;

                for (int i = 0; i < length; i++) {
                  if (timestampAsBytes[offset + i] == ':') {
                    hasColon = true;
                    break;
                  }
                }

                if (hasColon) {
                  hour = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);
                  minutes = StringUtils.getInt(timestampAsBytes, offset + 3, offset + 5);
                  seconds = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8);

                  year = 1970;
                  month = 1;
                  day = 1;

                  break;
                }

                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4);
                month = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6);
                day = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8);

                year -= 1900;
                month--;

                break;
              }

            case 6:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);

                if (year <= 69) {
                  year = (year + 100);
                }

                year += 1900;

                month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4);
                day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6);

                break;
              }

            case 4:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);

                if (year <= 69) {
                  year = (year + 100);
                }

                month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4);

                day = 1;

                break;
              }

            case 2:
              {
                year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2);

                if (year <= 69) {
                  year = (year + 100);
                }

                year += 1900;
                month = 1;
                day = 1;

                break;
              }

            default:
              throw new java.sql.SQLException(
                  "Bad format for Timestamp '"
                      + StringUtils.toString(timestampAsBytes)
                      + "' in column "
                      + (columnIndex + 1)
                      + ".",
                  SQLError.SQL_STATE_ILLEGAL_ARGUMENT);
          }

          if (!rs.useLegacyDatetimeCode) {
            return TimeUtil.fastTimestampCreate(
                tz, year, month, day, hour, minutes, seconds, nanos);
          }

          return TimeUtil.changeTimezone(
              conn,
              sessionCalendar,
              targetCalendar,
              rs.fastTimestampCreate(
                  sessionCalendar, year, month, day, hour, minutes, seconds, nanos),
              conn.getServerTimezoneTZ(),
              tz,
              rollForward);
        }
      }
    } catch (RuntimeException e) {
      SQLException sqlEx =
          SQLError.createSQLException(
              "Cannot convert value '"
                  + getString(columnIndex, "ISO8859_1", conn)
                  + "' from column "
                  + (columnIndex + 1)
                  + " to TIMESTAMP.",
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor);
      sqlEx.initCause(e);

      throw sqlEx;
    }
  }
Exemplo n.º 21
0
  /**
   * 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);
    }
  }
Exemplo n.º 22
0
  protected Time getTimeFast(
      int columnIndex,
      byte[] timeAsBytes,
      int offset,
      int fullLength,
      Calendar targetCalendar,
      TimeZone tz,
      boolean rollForward,
      MySQLConnection conn,
      ResultSetImpl rs)
      throws SQLException {

    int hr = 0;
    int min = 0;
    int sec = 0;
    int nanos = 0;

    int decimalIndex = -1;

    try {

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

      boolean allZeroTime = true;
      boolean onlyTimePresent = false;

      for (int i = 0; i < fullLength; i++) {
        if (timeAsBytes[offset + i] == ':') {
          onlyTimePresent = true;
          break;
        }
      }

      for (int i = 0; i < fullLength; i++) {
        if (timeAsBytes[offset + i] == '.') {
          decimalIndex = i;
          break;
        }
      }

      for (int i = 0; i < fullLength; i++) {
        byte b = timeAsBytes[offset + i];

        if (b == ' ' || b == '-' || b == '/') {
          onlyTimePresent = false;
        }

        if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') {
          allZeroTime = false;

          break;
        }
      }

      if (!onlyTimePresent && allZeroTime) {
        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 '"
                  + StringUtils.toString(timeAsBytes)
                  + "' can not be represented as java.sql.Time",
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor);
        }

        // We're left with the case of 'round' to a time Java _can_
        // represent, which is '00:00:00'
        return rs.fastTimeCreate(targetCalendar, 0, 0, 0);
      }

      Field timeColField = this.metadata[columnIndex];

      int length = fullLength;

      if (decimalIndex != -1) {

        length = decimalIndex;

        if ((decimalIndex + 2) <= fullLength) {
          nanos = StringUtils.getInt(timeAsBytes, offset + decimalIndex + 1, offset + fullLength);

          int numDigits = (fullLength) - (decimalIndex + 1);

          if (numDigits < 9) {
            int factor = (int) (Math.pow(10, 9 - numDigits));
            nanos = nanos * factor;
          }
        } else {
          throw new IllegalArgumentException(); // re-thrown
          // further
          // down
          // with
          // a
          // much better error message
        }
      }

      if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) {

        switch (length) {
          case 19:
            { // YYYY-MM-DD hh:mm:ss
              hr = StringUtils.getInt(timeAsBytes, offset + length - 8, offset + length - 6);
              min = StringUtils.getInt(timeAsBytes, offset + length - 5, offset + length - 3);
              sec = StringUtils.getInt(timeAsBytes, offset + length - 2, offset + length);
            }

            break;
          case 14:
          case 12:
            {
              hr = StringUtils.getInt(timeAsBytes, offset + length - 6, offset + length - 4);
              min = StringUtils.getInt(timeAsBytes, offset + length - 4, offset + length - 2);
              sec = StringUtils.getInt(timeAsBytes, offset + length - 2, offset + length);
            }

            break;

          case 10:
            {
              hr = StringUtils.getInt(timeAsBytes, offset + 6, offset + 8);
              min = StringUtils.getInt(timeAsBytes, offset + 8, offset + 10);
              sec = 0;
            }

            break;

          default:
            throw SQLError.createSQLException(
                Messages.getString(
                        "ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257") //$NON-NLS-1$
                    + (columnIndex + 1)
                    + "("
                    + timeColField
                    + ").",
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                this.exceptionInterceptor);
        } /* endswitch */

        @SuppressWarnings("unused")
        SQLWarning precisionLost =
            new SQLWarning(
                Messages.getString(
                        "ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261") //$NON-NLS-1$
                    + columnIndex
                    + "("
                    + timeColField
                    + ").");
        /*
         * if (this.warningChain == null) { this.warningChain =
         * precisionLost; } else {
         * this.warningChain.setNextWarning(precisionLost); }
         */
      } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATETIME) {
        hr = StringUtils.getInt(timeAsBytes, offset + 11, offset + 13);
        min = StringUtils.getInt(timeAsBytes, offset + 14, offset + 16);
        sec = StringUtils.getInt(timeAsBytes, offset + 17, offset + 19);

        @SuppressWarnings("unused")
        SQLWarning precisionLost =
            new SQLWarning(
                Messages.getString(
                        "ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264") //$NON-NLS-1$
                    + (columnIndex + 1)
                    + "("
                    + timeColField
                    + ").");

        /*
         * if (this.warningChain == null) { this.warningChain =
         * precisionLost; } else {
         * this.warningChain.setNextWarning(precisionLost); }
         */
      } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) {
        return rs.fastTimeCreate(null, 0, 0, 0); // midnight on the
        // given
        // date
      } else {
        // convert a String to a Time
        if ((length != 5) && (length != 8)) {
          throw SQLError.createSQLException(
              Messages.getString("ResultSet.Bad_format_for_Time____267") // $NON-NLS-1$
                  + StringUtils.toString(timeAsBytes)
                  + Messages.getString("ResultSet.___in_column__268")
                  + (columnIndex + 1),
              SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
              this.exceptionInterceptor);
        }

        hr = StringUtils.getInt(timeAsBytes, offset + 0, offset + 2);
        min = StringUtils.getInt(timeAsBytes, offset + 3, offset + 5);
        sec = (length == 5) ? 0 : StringUtils.getInt(timeAsBytes, offset + 6, offset + 8);
      }

      Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew();

      if (!rs.useLegacyDatetimeCode) {
        // TODO: return rs.fastTimeCreate(targetCalendar, hr, min, sec, nanos);
        // java.sql.Time doesn't contain fractional part, so PreparedStatement.setTime/getTime can't
        // deal with TIME(n) fractional part.
        // There may be better mappings to high-precision time coming in JDBC-5 with the adoption of
        // JSR-310.
        return rs.fastTimeCreate(targetCalendar, hr, min, sec);
      }

      synchronized (sessionCalendar) {
        return TimeUtil.changeTimezone(
            conn,
            sessionCalendar,
            targetCalendar,
            rs.fastTimeCreate(sessionCalendar, hr, min, sec),
            conn.getServerTimezoneTZ(),
            tz,
            rollForward);
        // TODO: min, sec, nanos), conn.getServerTimezoneTZ(), tz,
        // java.sql.Time doesn't contain fractional part, so PreparedStatement.setTime/getTime can't
        // deal with TIME(n) fractional part.
        // There may be better mappings to high-precision time coming in JDBC-5 with the adoption of
        // JSR-310.
      }
    } catch (RuntimeException ex) {
      SQLException sqlEx =
          SQLError.createSQLException(
              ex.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor);
      sqlEx.initCause(ex);

      throw sqlEx;
    }
  }
  /**
   * Returns the backing-store factory for HSQL syntax. If the cached tables are not available, they
   * will be created now from the SQL scripts bundled in this plugin.
   *
   * @param hints A map of hints, including the low-level factories to use for CRS creation.
   * @return The EPSG factory using HSQL syntax.
   * @throws SQLException if connection to the database failed.
   */
  protected AbstractAuthorityFactory createBackingStore(final Hints hints) throws SQLException {
    final DataSource source = getDataSource();
    final File directory = getDirectory(source);
    directory.mkdirs();
    if (!dataExists(directory)) {
      FileLock lock = null;
      try {
        // get an exclusive lock
        lock = acquireLock(directory);

        // if after getting the lock the database is still incomplete let's work on it
        if (!dataExists(directory)) {
          /*
           * HSQL has created automatically an empty database. We need to populate it.
           * Executes the SQL scripts bundled in the JAR. In theory, each line contains
           * a full SQL statement. For this plugin however, we have compressed "INSERT
           * INTO" statements using Compactor class in this package.
           */
          final Logger logger = Logging.getLogger(LOGGER);
          final LogRecord record =
              Loggings.format(Level.INFO, LoggingKeys.CREATING_CACHED_EPSG_DATABASE_$1, VERSION);
          record.setLoggerName(logger.getName());
          logger.log(record);

          ZipInputStream zin =
              new ZipInputStream(ThreadedH2EpsgFactory.class.getResourceAsStream(ZIP_FILE));
          ZipEntry ze = null;
          byte[] buf = new byte[1024];
          int read = 0;
          while ((ze = zin.getNextEntry()) != null) {
            File file = new File(directory, ze.getName());
            if (file.exists()) {
              file.delete();
            }
            FileOutputStream fout = new FileOutputStream(file);
            while ((read = zin.read(buf)) > 0) {
              fout.write(buf, 0, read);
            }
            zin.closeEntry();
            fout.close();
          }
          zin.close();

          // mark the successful creation
          File marker = new File(directory, MARKER_FILE);
          if (marker.exists()) {
            marker.delete();
          }
          marker.createNewFile();

          setReadOnly(directory);
        }
      } catch (IOException exception) {
        SQLException e = new SQLException(Errors.format(ErrorKeys.CANT_READ_$1, ZIP_FILE));
        e.initCause(exception); // TODO: inline cause when we will be allowed to target Java 6.
        throw e;
      } finally {
        if (lock != null) {
          try {
            lock.release();
            lock.channel().close();
            new File(directory, LOCK_FILE).delete();
          } catch (IOException e) {
            // does not matter, was just cleanup
          }
        }
      }
    }
    FactoryUsingAnsiSQL factory = new FactoryUsingAnsiSQL(hints, getDataSource().getConnection());
    factory.setValidationQuery("CALL NOW()");
    return factory;
  }
Exemplo n.º 24
0
  public Connection getConnection() throws SQLException {
    // If we are already connected, test to see if we are
    // still connected. If not, reset our connection.
    if (this.connection != null && this.connection.isClosed())
      try {
        Log.debug("Closing dead JDBC connection");
        this.connection.close();
      } catch (final SQLException e) {
        // We don't care. Ignore it.
      } finally {
        this.connection = null;
      }

    // If we are not connected, we should attempt to (re)connect now.
    if (this.connection == null) {
      Log.debug("Establishing JDBC connection");
      // Start out with no driver at all.
      Class loadedDriverClass = null;

      // Try the system class loader instead.
      try {
        loadedDriverClass = Class.forName(this.conObj.getJdbcType().getDriverClassName());
      } catch (final ClassNotFoundException e) {
        final SQLException e2 = new SQLException();
        e2.initCause(e);
        throw e2;
      }

      // Check it really is an instance of Driver.
      if (!Driver.class.isAssignableFrom(loadedDriverClass))
        throw new ClassCastException(Resources.get("driverClassNotJDBCDriver"));

      // Connect!
      final Properties properties = new Properties();
      properties.setProperty("user", this.conObj.getUserName());
      if (!this.conObj.getPassword().equals(""))
        properties.setProperty("password", this.conObj.getPassword());
      properties.setProperty("nullCatalogMeansCurrent", "false");
      /*
       * this.connection = DriverManager.getConnection( overrideDataLinkSchema == null ? this.conObj.getJdbcUrl():
       * (this.conObj.getJdbcUrl()) .replaceAll(this.getDataLinkSchema(), overrideDataLinkSchema), properties);
       */

      this.connection =
          DriverManager.getConnection(
              this.conObj.getJdbcUrl(), conObj.getUserName(), conObj.getPassword());
      // Check the schema name.
      final DatabaseMetaData dmd = this.connection.getMetaData();
      final String catalog = this.connection.getCatalog();
      this.realSchemaName = this.getDataLinkSchema();
      ResultSet rs = dmd.getTables(catalog, this.realSchemaName, "%", null);
      if (!rs.next()) {
        rs = dmd.getTables(catalog, this.realSchemaName.toUpperCase(), "%", null);
        if (rs.next()) this.realSchemaName = this.realSchemaName.toUpperCase();
      }
      if (!rs.next()) {
        rs = dmd.getTables(catalog, this.realSchemaName.toLowerCase(), "%", null);
        if (rs.next()) this.realSchemaName = this.realSchemaName.toLowerCase();
      }
      rs.close();
    }

    // Return the connection.
    return this.connection;
  }
Exemplo n.º 25
0
  /**
   * This method will send a fetch rowset command to the server.
   *
   * @param maxRowCnt the maximum rowset count to return
   * @param maxRowLen the maximum row length to return
   * @param sqlAsyncEnable a flag to enable/disable asynchronies execution
   * @param queryTimeout the number of seconds before the query times out
   * @retrun a FetchPerfReply class representing the reply from the ODBC server is returned
   * @exception A SQLException is thrown
   */
  FetchReply Fetch(
      int sqlAsyncEnable,
      int queryTimeout,
      int stmtHandle,
      int stmtCharset,
      int maxRowCnt,
      String cursorName,
      int cursorCharset,
      String stmtOptions)
      throws SQLException {

    try {
      getInputOutput().setTimeout(m_ic.t4props_.getNetworkTimeout());

      LogicalByteArray wbuffer =
          FetchMessage.marshal(
              m_dialogueId,
              sqlAsyncEnable,
              queryTimeout,
              stmtHandle,
              m_stmtLabel,
              stmtCharset,
              maxRowCnt,
              0 // infinite row size
              ,
              cursorName,
              cursorCharset,
              stmtOptions,
              this.m_ic);

      LogicalByteArray rbuffer = getReadBuffer(TRANSPORT.SRVR_API_SQLFETCH, wbuffer);

      //
      // Process output parameters
      //
      FetchReply frr = new FetchReply(rbuffer, m_ic);

      return frr;
    } // end try
    catch (SQLException se) {
      throw se;
    } catch (CharacterCodingException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_,
              m_locale,
              "translation_of_parameter_failed",
              "FetchMessage",
              e.getMessage());
      se.initCause(e);
      throw se;
    } catch (UnsupportedCharsetException e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "unsupported_encoding", e.getCharsetName());
      se.initCause(e);
      throw se;
    } catch (Exception e) {
      SQLException se =
          HPT4Messages.createSQLException(
              m_ic.t4props_, m_locale, "fetch_perf_message_error", e.getMessage());

      se.initCause(e);
      throw se;
    } // end catch
  } // end FetchPerf
Exemplo n.º 26
0
  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;
  }
Exemplo n.º 27
0
 /**
  * Convert an exception to a fulltext exception.
  *
  * @param e the original exception
  * @return the converted SQL exception
  */
 protected static SQLException convertException(Exception e) {
   SQLException e2 = new SQLException("Error while indexing document", "FULLTEXT");
   e2.initCause(e);
   return e2;
 }