Search in sources :

Example 46 with SQLException

use of java.sql.SQLException in project hive by apache.

the class HiveStatement method runAsyncOnServer.

private void runAsyncOnServer(String sql) throws SQLException {
    checkConnection("execute");
    closeClientOperation();
    initFlags();
    TExecuteStatementReq execReq = new TExecuteStatementReq(sessHandle, sql);
    /**
     * Run asynchronously whenever possible
     * Currently only a SQLOperation can be run asynchronously,
     * in a background operation thread
     * Compilation can run asynchronously or synchronously and execution run asynchronously
     */
    execReq.setRunAsync(true);
    execReq.setConfOverlay(sessConf);
    execReq.setQueryTimeout(queryTimeout);
    try {
        TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
        Utils.verifySuccessWithInfo(execResp.getStatus());
        stmtHandle = execResp.getOperationHandle();
        isExecuteStatementFailed = false;
    } catch (SQLException eS) {
        isExecuteStatementFailed = true;
        throw eS;
    } catch (Exception ex) {
        isExecuteStatementFailed = true;
        throw new SQLException(ex.toString(), "08S01", ex);
    }
}
Also used : SQLException(java.sql.SQLException) TExecuteStatementReq(org.apache.hive.service.rpc.thrift.TExecuteStatementReq) TExecuteStatementResp(org.apache.hive.service.rpc.thrift.TExecuteStatementResp) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLTimeoutException(java.sql.SQLTimeoutException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException)

Example 47 with SQLException

use of java.sql.SQLException in project hive by apache.

the class HiveConnection method openSession.

private void openSession() throws SQLException {
    TOpenSessionReq openReq = new TOpenSessionReq();
    Map<String, String> openConf = new HashMap<String, String>();
    // for remote JDBC client, try to set the conf var using 'set foo=bar'
    for (Entry<String, String> hiveConf : connParams.getHiveConfs().entrySet()) {
        openConf.put("set:hiveconf:" + hiveConf.getKey(), hiveConf.getValue());
    }
    // For remote JDBC client, try to set the hive var using 'set hivevar:key=value'
    for (Entry<String, String> hiveVar : connParams.getHiveVars().entrySet()) {
        openConf.put("set:hivevar:" + hiveVar.getKey(), hiveVar.getValue());
    }
    // switch the database
    openConf.put("use:database", connParams.getDbName());
    // set the fetchSize
    openConf.put("set:hiveconf:hive.server2.thrift.resultset.default.fetch.size", Integer.toString(fetchSize));
    // set the session configuration
    Map<String, String> sessVars = connParams.getSessionVars();
    if (sessVars.containsKey(HiveAuthFactory.HS2_PROXY_USER)) {
        openConf.put(HiveAuthFactory.HS2_PROXY_USER, sessVars.get(HiveAuthFactory.HS2_PROXY_USER));
    }
    openReq.setConfiguration(openConf);
    // Store the user name in the open request in case no non-sasl authentication
    if (JdbcConnectionParams.AUTH_SIMPLE.equals(sessConfMap.get(JdbcConnectionParams.AUTH_TYPE))) {
        openReq.setUsername(sessConfMap.get(JdbcConnectionParams.AUTH_USER));
        openReq.setPassword(sessConfMap.get(JdbcConnectionParams.AUTH_PASSWD));
    }
    try {
        TOpenSessionResp openResp = client.OpenSession(openReq);
        // validate connection
        Utils.verifySuccess(openResp.getStatus());
        if (!supportedProtocols.contains(openResp.getServerProtocolVersion())) {
            throw new TException("Unsupported Hive2 protocol");
        }
        protocol = openResp.getServerProtocolVersion();
        sessHandle = openResp.getSessionHandle();
        // Update fetchSize if modified by server
        String serverFetchSize = openResp.getConfiguration().get("hive.server2.thrift.resultset.default.fetch.size");
        if (serverFetchSize != null) {
            fetchSize = Integer.parseInt(serverFetchSize);
        }
    } catch (TException e) {
        LOG.error("Error opening session", e);
        throw new SQLException("Could not establish connection to " + jdbcUriString + ": " + e.getMessage(), " 08S01", e);
    }
    isClosed = false;
}
Also used : TException(org.apache.thrift.TException) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) TOpenSessionReq(org.apache.hive.service.rpc.thrift.TOpenSessionReq) TOpenSessionResp(org.apache.hive.service.rpc.thrift.TOpenSessionResp)

Example 48 with SQLException

use of java.sql.SQLException in project hive by apache.

the class HiveConnection method renewDelegationToken.

public void renewDelegationToken(String tokenStr) throws SQLException {
    TRenewDelegationTokenReq cancelReq = new TRenewDelegationTokenReq(sessHandle, tokenStr);
    try {
        TRenewDelegationTokenResp renewResp = client.RenewDelegationToken(cancelReq);
        Utils.verifySuccess(renewResp.getStatus());
        return;
    } catch (TException e) {
        throw new SQLException("Could not renew token: " + e.getMessage(), " 08S01", e);
    }
}
Also used : TException(org.apache.thrift.TException) SQLException(java.sql.SQLException) TRenewDelegationTokenResp(org.apache.hive.service.rpc.thrift.TRenewDelegationTokenResp) TRenewDelegationTokenReq(org.apache.hive.service.rpc.thrift.TRenewDelegationTokenReq)

Example 49 with SQLException

use of java.sql.SQLException in project hive by apache.

the class HiveConnection method getHttpClient.

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE.equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH)));
    String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();
    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : sessConfMap.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
       * Add an interceptor which sets the appropriate header in the request.
       * It does the kerberos authentication and get the final service ticket,
       * for sending to the server before every request.
       * In https mode, the entire information is encrypted
       */
        requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        // Check for delegation token, if present add it in the header
        String tokenStr = getClientDelegationToken(sessConfMap);
        if (tokenStr != null) {
            requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders);
        } else {
            /**
       * Add an interceptor to pass username/password in the header.
       * In https mode, the entire information is encrypted
       */
            requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders);
        }
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom().setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

            @Override
            public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
                int statusCode = response.getStatusLine().getStatusCode();
                boolean ret = statusCode == 401 && executionCount <= 1;
                // interceptor
                if (ret) {
                    context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                }
                return ret;
            }

            @Override
            public long getRetryInterval() {
                // Immediate retry
                return 0;
            }
        });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Add an interceptor to add in an XSRF header
    httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLConnectionSocketFactory socketFactory;
        SSLContext sslContext;
        /**
       * The code within the try block throws: SSLInitializationException, KeyStoreException,
       * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException &
       * UnrecoverableKeyException. We don't want the client to retry on any of these,
       * hence we catch all and throw a SQLException.
       */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLConnectionSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build();
                socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null));
            }
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();
            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Savepoint(java.sql.Savepoint) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 50 with SQLException

use of java.sql.SQLException in project hive by apache.

the class HiveConnection method getDelegationToken.

public String getDelegationToken(String owner, String renewer) throws SQLException {
    TGetDelegationTokenReq req = new TGetDelegationTokenReq(sessHandle, owner, renewer);
    try {
        TGetDelegationTokenResp tokenResp = client.GetDelegationToken(req);
        Utils.verifySuccess(tokenResp.getStatus());
        return tokenResp.getDelegationToken();
    } catch (TException e) {
        throw new SQLException("Could not retrieve token: " + e.getMessage(), " 08S01", e);
    }
}
Also used : TException(org.apache.thrift.TException) SQLException(java.sql.SQLException) TGetDelegationTokenReq(org.apache.hive.service.rpc.thrift.TGetDelegationTokenReq) TGetDelegationTokenResp(org.apache.hive.service.rpc.thrift.TGetDelegationTokenResp)

Aggregations

SQLException (java.sql.SQLException)6792 PreparedStatement (java.sql.PreparedStatement)3048 ResultSet (java.sql.ResultSet)2426 Connection (java.sql.Connection)1871 ArrayList (java.util.ArrayList)972 Test (org.junit.Test)873 Statement (java.sql.Statement)779 IOException (java.io.IOException)341 List (java.util.List)335 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)298 Properties (java.util.Properties)255 DatabaseException (net.jforum.exceptions.DatabaseException)249 HashMap (java.util.HashMap)232 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)184 Timestamp (java.sql.Timestamp)171 CallableStatement (java.sql.CallableStatement)165 DbConnection (com.zimbra.cs.db.DbPool.DbConnection)160 DalHints (com.ctrip.platform.dal.dao.DalHints)159 Map (java.util.Map)125 Date (java.util.Date)123