List of usage examples for java.sql SQLException getCause
public synchronized Throwable getCause()
From source file:org.apache.hive.service.cli.operation.OperationManager.java
public RowSet getOperationLogRowSet(OperationHandle opHandle, FetchOrientation orientation, long maxRows) throws HiveSQLException { // get the OperationLog object from the operation OperationLog operationLog = getOperation(opHandle).getOperationLog(); if (operationLog == null) { throw new HiveSQLException("Couldn't find log associated with operation handle: " + opHandle); }/*from ww w . java 2 s.co m*/ // read logs List<String> logs; try { logs = operationLog.readOperationLog(isFetchFirst(orientation), maxRows); } catch (SQLException e) { throw new HiveSQLException(e.getMessage(), e.getCause()); } // convert logs to RowSet TableSchema tableSchema = new TableSchema(getLogSchema()); RowSet rowSet = RowSetFactory.create(tableSchema, getOperation(opHandle).getProtocolVersion()); for (String log : logs) { rowSet.addRow(new String[] { log }); } return rowSet; }
From source file:com.ipcglobal.fredimportcdh.TsvsToImpala.java
/** * Process tables./*ww w . j a va 2s. com*/ * * @throws Exception the exception */ private void processTables() throws Exception { String jdbcImpalaDriverClass = this.properties.getProperty("jdbcImpalaDriverClass").trim(); String jdbcImpalaUrl = this.properties.getProperty("jdbcImpalaUrl").trim(); String jdbcImpalaLogin = this.properties.getProperty("jdbcImpalaLogin").trim(); String jdbcImpalaPassword = this.properties.getProperty("jdbcImpalaPassword").trim(); String databaseNameFred = this.properties.getProperty("databaseNameFred").trim(); String tableNameFred = properties.getProperty("tableNameFred"); String stageTableSuffix = "_staging"; Connection con = null; Statement statement = null; String databaseTableName = databaseNameFred + "." + tableNameFred; String databaseStageTableName = databaseNameFred + "." + tableNameFred + stageTableSuffix; try { Class.forName(jdbcImpalaDriverClass); con = DriverManager.getConnection(jdbcImpalaUrl, jdbcImpalaLogin, jdbcImpalaPassword); statement = con.createStatement(); log.info("\tDrop/create internal and external staging table"); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseTableName); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName); log.info("\tCreate external staging table against the tsv's in HDFS"); statement.executeUpdate(createStageTableStatement(databaseStageTableName)); statement.executeUpdate("REFRESH " + databaseStageTableName); log.info("\tCreate internal table as select from external staging table"); String sqlCreateAs = "create table " + databaseTableName + " stored as parquet as select * from " + databaseStageTableName; statement.executeUpdate(sqlCreateAs); statement.executeUpdate("REFRESH " + databaseTableName); log.info("\tDrop the staging table"); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName); log.info("\tStart - COMPUTE STATS on internal table"); String sqlComputeStats = "COMPUTE STATS " + databaseTableName; try { long before = System.currentTimeMillis(); log.info(sqlComputeStats); statement.executeUpdate(sqlComputeStats); log.info("\tCOMPUTE STATS Insert Ok, Elapsed=" + convertMSecsToHMmSs(System.currentTimeMillis() - before)); } catch (Exception e) { log.error("COMPUTE STATS, statement=" + sqlComputeStats, e); throw e; } } catch (SQLException se) { log.error(se); log.error("Cause: " + se.getCause()); log.error("getErrorCode: " + se.getErrorCode()); log.error("getSQLState: " + se.getSQLState()); se.printStackTrace(); throw se; } catch (Exception e) { log.error(e); e.printStackTrace(); throw e; } finally { try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (con != null) con.close(); } catch (Exception e) { } } }
From source file:fr.paris.lutece.util.sql.Transaction.java
/** * Rollback the transaction//from w ww . j a v a 2 s. c o m * @param e The exception that cause the rollback */ public void rollback(Exception e) { if (e != null) { _logger.error("Transaction Error - Rollback in progress " + e.getMessage(), e.getCause()); } try { if (_connection != null) { _connection.rollback(); _logger.debug("Plugin : '" + _strPluginName + "' - ROLLBACK TRANSACTION"); } else { _logger.debug("Plugin : '" + _strPluginName + "' - TRANSACTION HAS ALREADY BEEN ROLLED BACK"); } } catch (SQLException ex) { _logger.error("Transaction Error - Rollback error : " + ex.getMessage(), ex.getCause()); } finally { closeTransaction(ROLLEDBACK); } }
From source file:org.dspace.app.oai.DIDLCrosswalk.java
public String createMetadata(Object nativeItem) throws CannotDisseminateFormatException { Item item = ((HarvestedItemInfo) nativeItem).item; StringBuffer metadata = new StringBuffer(); String itemhandle = item.getHandle(); String strMaxSize = ConfigurationManager.getProperty("oai", "didl.maxresponse"); int maxsize = MAXRESPONSE_INLINE_BITSTREAM; if (strMaxSize != null) { maxsize = Integer.parseInt(strMaxSize); }/*from w w w . j a v a2 s .co m*/ String currdate = ServerVerb.createResponseDate(new Date()); metadata.append("<didl:DIDL ").append(" xmlns:didl=\"urn:mpeg:mpeg21:2002:02-DIDL-NS\" ") .append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ") .append("xsi:schemaLocation=\"urn:mpeg:mpeg21:2002:02-DIDL-NS http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-21_schema_files/did/didl.xsd \">") .append("<didl:DIDLInfo>") .append("<dcterms:created xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://purl.org/dc/terms/ \">") .append(currdate).append("</dcterms:created> </didl:DIDLInfo>").append("<didl:Item id=\"") .append("uuid-" + UUIDFactory.generateUUID().toString() + "\">"); metadata.append("<didl:Descriptor>").append("<didl:Statement mimeType=\"application/xml; charset=utf-8\">") .append("<dii:Identifier xmlns:dii=\"urn:mpeg:mpeg21:2002:01-DII-NS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:mpeg:mpeg21:2002:01-DII-NS http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-21_schema_files/dii/dii.xsd\">") .append("urn:hdl:").append(itemhandle).append("</dii:Identifier>").append("</didl:Statement>") .append("</didl:Descriptor>"); metadata.append("<didl:Descriptor>").append("<didl:Statement mimeType=\"application/xml; charset=utf-8\">"); // delegate the metadata section to another crosswalk metadata.append(metadataCrosswalk.createMetadata(nativeItem)); metadata.append("</didl:Statement>").append("</didl:Descriptor>"); /**putfirst item here**/ //**CYCLE HERE!!!!**// try { Bundle[] bundles = item.getBundles("ORIGINAL"); if (bundles.length != 0) { /**cycle bundles**/ for (int i = 0; i < bundles.length; i++) { int flag = 0; Bitstream[] bitstreams = bundles[i].getBitstreams(); /**cycle bitstreams**/ for (int k = 0; k < bitstreams.length; k++) { // Skip internal types if (!bitstreams[k].getFormat().isInternal()) { if (flag == 0) { flag = 1; } metadata.append("<didl:Component id=" + "\"uuid-" + UUIDFactory.generateUUID().toString() + "\">"); if (bitstreams[k].getSize() > maxsize) { metadata.append( "<didl:Resource ref=\"" + ConfigurationManager.getProperty("dspace.url") + "/bitstream/" + itemhandle + "/" + bitstreams[k].getSequenceID() + "/" + bitstreams[k].getName()); metadata.append("\" mimeType=\""); metadata.append(bitstreams[k].getFormat().getMIMEType()); metadata.append("\">"); metadata.append("</didl:Resource>"); } else { try { metadata.append("<didl:Resource mimeType=\""); metadata.append(bitstreams[k].getFormat().getMIMEType()); metadata.append("\" encoding=\"base64\">"); /* * Assume that size of in-line bitstreams will always be * smaller than MAXINT bytes */ int intSize = (int) bitstreams[k].getSize(); byte[] buffer = new byte[intSize]; Context contextl = new Context(); InputStream is = BitstreamStorageManager.retrieve(contextl, bitstreams[k].getID()); BufferedInputStream bis = new BufferedInputStream(is); try { bis.read(buffer); } finally { if (bis != null) { try { bis.close(); } catch (IOException ioe) { } } if (is != null) { try { is.close(); } catch (IOException ioe) { } } } contextl.complete(); String encoding = new String(Base64.encodeBase64(buffer), "ASCII"); metadata.append(encoding); } catch (Exception ex) { log.error("Error creating resource didl", ex); metadata.append("<didl:Resource ref=\"") .append(ConfigurationManager.getProperty("dspace.url")) .append("/bitstream/").append(itemhandle).append("/") .append(bitstreams[k].getSequenceID()).append("/") .append(bitstreams[k].getName()); metadata.append("\" mimeType=\""); metadata.append(bitstreams[k].getFormat().getMIMEType()); metadata.append("\">"); } metadata.append("</didl:Resource>"); } metadata.append("</didl:Component>"); } /*end bitstream cycle*/ } /*end bundle cycle*/ } } } catch (SQLException sqle) { System.err.println("Caught exception:" + sqle.getCause()); log.error("Database error", sqle); } //**END CYCLE HERE **// metadata.append("</didl:Item>").append("</didl:DIDL>"); return metadata.toString(); }
From source file:fr.paris.lutece.util.sql.Transaction.java
/** * Close the transaction/* w w w . ja v a 2 s . co m*/ * @param nStatus The status of the transaction */ private void closeTransaction(int nStatus) { _nStatus = nStatus; try { if (_statement != null) { _statement.close(); } // Restore the autocommit configuration of the connection if (_connection != null) { _connection.setAutoCommit(_bAutoCommit); } } catch (SQLException ex) { _logger.error("Transaction Error - Unable to close transaction " + ex.getMessage(), ex.getCause()); } finally { _connectionService.freeConnection(_connection); _connection = null; } }
From source file:com.scistor.queryrouter.server.impl.JdbcHandlerImpl.java
@Override public Map<String, String> queryForMeta(String tableName) { long begin = System.currentTimeMillis(); Map<String, String> result = Maps.newConcurrentMap(); Connection conn = null;//from w ww .j a v a 2 s. c om PreparedStatement pst = null; try { conn = this.getJdbcTemplate().getDataSource().getConnection(); DatabaseMetaData dbMetaData = conn.getMetaData(); if (StringUtils.isNotEmpty(tableName)) { pst = conn.prepareStatement(String.format("select * from %s where 1=2", tableName)); ResultSetMetaData rsd = pst.executeQuery().getMetaData(); for (int i = 0; i < rsd.getColumnCount(); i++) { result.put(rsd.getColumnName(i + 1), rsd.getColumnTypeName(i + 1)); } } } catch (SQLException e1) { logger.error("queryId:{} select meta error:{}", 1, e1.getCause().getMessage()); } finally { JdbcUtils.closeConnection(conn); JdbcUtils.closeStatement(pst); logger.info("queryId:{} select meta cost:{} ms resultsize:{}", 1, System.currentTimeMillis() - begin, result.size()); } return result; }
From source file:com.taobao.datax.plugins.reader.oraclereader.OracleReaderRowidSplitter.java
private List<Map<RowidKey, String>> analyzeRowids(String tablet, String sql) { List<Map<RowidKey, String>> rowids = new ArrayList<Map<RowidKey, String>>(); ResultSet rs = null;//from w ww. ja v a 2 s. co m try { this.logger.info(String.format("Analyze Rowid query: %s .", sql)); rs = DBUtils.query(this.connection, sql); if (!rs.next()) { logger.info(String.format("Table %s rowid is empty, use none-rowid split mechanism .", tablet)); Map<RowidKey, String> perRowid = new HashMap<RowidKey, String>(); perRowid.put(RowidKey.tableName, tablet); rowids.add(perRowid); } else { do { String minRowid = rs.getString(1); String maxRowid = rs.getString(2); if (StringUtils.isBlank(minRowid) || StringUtils.isBlank(maxRowid)) { continue; } Map<RowidKey, String> perRowid = new HashMap<RowidKey, String>(); perRowid.put(RowidKey.tableName, tablet); perRowid.put(RowidKey.tableMinRowid, minRowid); perRowid.put(RowidKey.tableMaxRowid, maxRowid); rowids.add(perRowid); } while (rs.next()); } return rowids; } catch (SQLException e) { // TODO Auto-generated catch block logger.error(ExceptionTracker.trace(e)); throw new IllegalStateException(e.getCause()); } finally { DBUtils.closeResultSet(rs); } }
From source file:fuel.gui.stats.MotorStatsPanel.java
private void refreshGraphs(Motorcycle motor) { graphContainer.removeAll();//from www. jav a 2s . c o m if (motor != null) { DefaultPieDataset usageDataset = new DefaultPieDataset(); try { ResultSet thisMotor = database .Query("SELECT SUM(distance) FROM fuelrecords WHERE motorcycleId = " + motor.getId(), true); ResultSet otherMotors = database.Query( "SELECT SUM(distance) FROM fuelrecords WHERE NOT motorcycleId = " + motor.getId(), true); thisMotor.next(); otherMotors.next(); usageDataset.setValue(motor.toString(), thisMotor.getInt("1")); usageDataset.setValue("Andere motoren", otherMotors.getInt("1")); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause()); } JFreeChart usagePiechart = ChartFactory.createPieChart3D("", usageDataset, true, true, false); PiePlot3D plot3 = (PiePlot3D) usagePiechart.getPlot(); plot3.setForegroundAlpha(0.6f); //plot3.setCircular(true); JPanel usagePiechartPanel = new ChartPanel(usagePiechart); usagePiechartPanel .setBorder(BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Motorgebruik"))); usagePiechartPanel.setPreferredSize(new java.awt.Dimension(240, 240)); usagePiechartPanel.setLayout(new BorderLayout()); DefaultPieDataset stationDataset = new DefaultPieDataset(); try { for (Station station : database.getStations()) { ResultSet numberStations = database.Query( "SELECT DISTINCT stationId FROM fuelrecords WHERE stationId = " + station.getId(), true); if (numberStations.next()) { ResultSet otherMotors = database.Query("SELECT COUNT(*) FROM fuelrecords WHERE stationId = " + station.getId() + " AND motorcycleId = " + motor.getId(), true); otherMotors.next(); if (otherMotors.getInt("1") > 0) { stationDataset.setValue(station.toString(), otherMotors.getInt("1")); } } } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause()); } JFreeChart stationPiechart = ChartFactory.createPieChart3D("", stationDataset, true, true, false); PiePlot3D plot2 = (PiePlot3D) stationPiechart.getPlot(); plot2.setForegroundAlpha(0.6f); //plot3.setCircular(true); JPanel stationPiechartPanel = new ChartPanel(stationPiechart); stationPiechartPanel.setBorder( BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Tankstation verhouding"))); stationPiechartPanel.setPreferredSize(new java.awt.Dimension(240, 240)); stationPiechartPanel.setLayout(new BorderLayout()); DefaultPieDataset fuelDataset = new DefaultPieDataset(); try { ResultSet numberResults = database.Query("SELECT DISTINCT typeOfGas FROM fuelrecords", true); while (numberResults.next()) { ResultSet thisStation = database.Query( "SELECT SUM(liter) FROM fuelrecords WHERE typeOfGas = '" + numberResults.getString("typeOfGas") + "'AND motorcycleId = " + motor.getId(), true); thisStation.next(); if (thisStation.getDouble("1") > 0) { fuelDataset.setValue(numberResults.getString("TYPEOFGAS"), thisStation.getDouble("1")); } } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause()); } JFreeChart fuelPieChart = ChartFactory.createPieChart3D("", fuelDataset, true, true, false); PiePlot3D plot1 = (PiePlot3D) fuelPieChart.getPlot(); plot1.setForegroundAlpha(0.6f); //plot3.setCircular(true); JPanel fuelPieChartPanel = new ChartPanel(fuelPieChart); fuelPieChartPanel.setBorder( BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Brandstof verhouding"))); fuelPieChartPanel.setPreferredSize(new java.awt.Dimension(240, 240)); DefaultCategoryDataset barDataset = new DefaultCategoryDataset(); try { ResultSet motorThing = database .Query("SELECT distance/liter,date FROM fuelrecords WHERE motorcycleId = " + motor.getId() + " ORDER BY date ASC", true); while (motorThing.next()) { barDataset.addValue(motorThing.getDouble("1"), motorThing.getString("DATE"), "Verbruik"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause()); } JFreeChart barChart = ChartFactory.createBarChart3D("", // chart title "", // domain axis label "Aantal", // range axis label barDataset, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips? false // URLs? ); CategoryPlot plot = barChart.getCategoryPlot(); BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer(); renderer.setDrawBarOutline(false); ChartPanel barChartPanel = new ChartPanel(barChart); barChartPanel.getChartRenderingInfo().setEntityCollection(null); barChartPanel.setBorder(BorderFactory.createTitledBorder("Verbruik")); barChartPanel.setPreferredSize(new java.awt.Dimension(320, 240)); barChartPanel.setLayout(new BorderLayout()); JPanel piePanel = new JPanel(new GridLayout(0, 3)); piePanel.add(usagePiechartPanel); piePanel.add(stationPiechartPanel); piePanel.add(fuelPieChartPanel); //uitgaven DefaultPieDataset expensesDataset = new DefaultPieDataset(); try { Map<String, ResultSet> allCosts = new HashMap<String, ResultSet>(); ResultSet fuelCosts = database .Query("SELECT SUM(cost) FROM fuelrecords WHERE motorcycleId = " + motor.getId(), true); allCosts.put("Brandstof", fuelCosts); ResultSet expenses = database.Query("SELECT DISTINCT categoryid FROM expenses", true); while (expenses.next()) { ResultSet set = database.Query("SELECT SUM(costs) FROM expenses WHERE categoryid = " + expenses.getInt("categoryid") + " AND motorcycleid = " + motor.getId(), true); ResultSet set2 = database .Query("SELECT name FROM categories WHERE id = " + expenses.getInt("categoryid"), true); set2.next(); allCosts.put(set2.getString("name"), set); } for (Map.Entry<String, ResultSet> element : allCosts.entrySet()) { element.getValue().next(); if (element.getValue().getInt("1") > 0) { expensesDataset.setValue(element.getKey(), element.getValue().getInt("1")); } } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage() + ex.getCause()); } JFreeChart expensesPiechart = ChartFactory.createPieChart3D("", expensesDataset, true, true, false); PiePlot3D plot4 = (PiePlot3D) expensesPiechart.getPlot(); plot4.setForegroundAlpha(0.6f); JPanel expensesPiePanel = new ChartPanel(expensesPiechart); expensesPiePanel .setBorder(BorderFactory.createTitledBorder(BorderFactory.createTitledBorder("Uitgaven"))); expensesPiePanel.setPreferredSize(new java.awt.Dimension(240, 240)); expensesPiePanel.setLayout(new BorderLayout()); graphContainer.add(piePanel); graphContainer.add(barChartPanel); graphContainer.add(expensesPiePanel); } revalidate(); repaint(); }
From source file:BQJDBC.QueryResultTest.Timeouttest.java
@Test public void QueryResultTest03() { final String sql = "SELECT COUNT(DISTINCT web100_log_entry.connection_spec.remote_ip) AS num_clients FROM [guid754187384106:m_lab.2010_01] " + "WHERE IS_EXPLICITLY_DEFINED(web100_log_entry.connection_spec.remote_ip) AND IS_EXPLICITLY_DEFINED(web100_log_entry.log_time) " + "AND web100_log_entry.log_time > 1262304000 AND web100_log_entry.log_time < 1262476800"; final String description = "A sample query from google, but we don't have Access for the query table #ERROR #accessDenied #403"; this.logger.info("Test number: 03"); this.logger.info("Running query:" + sql); this.logger.debug(description); try {/* w w w .ja va2s. c om*/ Timeouttest.con.createStatement().executeQuery(sql); } catch (SQLException e) { this.logger.debug("SQLexception" + e.toString()); // fail("SQLException" + e.toString()); Assert.assertTrue(e.getCause().toString() .contains("Access Denied: Table measurement-lab:m_lab.2010_01: QUERY_TABLE")); } }
From source file:org.apache.hive.jdbc.TestSSL.java
/*** * Tests to ensure SSLv2 and SSLv3 are disabled *///from w ww . j a v a 2 s .co m @Test public void testSSLVersion() throws Exception { Assume.assumeTrue(execCommand("which openssl") == 0); // we need openssl Assume.assumeTrue(System.getProperty("os.name").toLowerCase().contains("linux")); // we depend on linux openssl exit codes setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); // Start HS2 with SSL miniHS2.start(confOverlay); // make SSL connection hs2Conn = DriverManager .getConnection( miniHS2.getJdbcURL() + ";ssl=true;sslTrustStore=" + dataFileDir + File.separator + TRUST_STORE_NAME + ";trustStorePassword=" + KEY_STORE_PASSWORD, System.getProperty("user.name"), "bar"); hs2Conn.close(); Assert.assertEquals("Expected exit code of 1", 1, execCommand("openssl s_client -connect " + miniHS2.getHost() + ":" + miniHS2.getBinaryPort() + " -ssl2 < /dev/null")); Assert.assertEquals("Expected exit code of 1", 1, execCommand("openssl s_client -connect " + miniHS2.getHost() + ":" + miniHS2.getBinaryPort() + " -ssl3 < /dev/null")); miniHS2.stop(); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); // make SSL connection try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL() + ";ssl=true;sslTrustStore=" + dataFileDir + File.separator + TRUST_STORE_NAME + ";trustStorePassword=" + KEY_STORE_PASSWORD + "?hive.server2.transport.mode=" + HS2_HTTP_MODE + ";hive.server2.thrift.http.path=" + HS2_HTTP_ENDPOINT, System.getProperty("user.name"), "bar"); Assert.fail("Expected SQLException during connect"); } catch (SQLException e) { LOG.info("Expected exception: " + e, e); Assert.assertEquals("08S01", e.getSQLState().trim()); Throwable cause = e.getCause(); Assert.assertNotNull(cause); while (cause.getCause() != null) { cause = cause.getCause(); } Assert.assertEquals("org.apache.http.NoHttpResponseException", cause.getClass().getName()); Assert.assertTrue(cause.getMessage().contains("failed to respond")); } miniHS2.stop(); }