List of usage examples for java.sql SQLException printStackTrace
public void printStackTrace()
From source file:geo.controller.GeoCodeServlet.java
private ArrayList<Transaction> getAllTransactions() { try {/* w ww. j av a2 s .c o m*/ return TransactionDAO.getTransactionListToGeocode(); } catch (SQLException ex) { ex.printStackTrace(); } return null; }
From source file:Main.java
public Main() { try {/*from w w w . j a v a 2s. co m*/ SyncFactory.registerProvider("MySyncProvider"); Hashtable env = new Hashtable(); env.put(SyncFactory.ROWSET_SYNC_PROVIDER, "MySyncProvider"); crs = new CachedRowSetImpl(env); crs.execute(); // load data from custom RowSetReader System.out.println("Fetching from RowSet..."); while (crs.next()) { displayData(); } if (crs.isAfterLast() == true) { System.out.println("We have reached the end"); System.out.println("crs row: " + crs.getRow()); } System.out.println("And now backwards..."); while (crs.previous()) { displayData(); } // end while previous if (crs.isBeforeFirst()) { System.out.println("We have reached the start"); } crs.first(); if (crs.isFirst()) { System.out.println("We have moved to first"); } System.out.println("crs row: " + crs.getRow()); if (!crs.isBeforeFirst()) { System.out.println("We aren't before the first row."); } crs.last(); if (crs.isLast()) { System.out.println("...and now we have moved to the last"); } System.out.println("crs row: " + crs.getRow()); if (!crs.isAfterLast()) { System.out.println("we aren't after the last."); } } catch (SQLException e) { e.printStackTrace(); System.err.println("SQLException: " + e.getMessage()); } }
From source file:com.mfast.evaluations.DCAppSession.java
public void run() { try {//from w w w.j a v a2 s . co m String DCAppResponse = sendGet(); Gson gson = new Gson(); // get a database connection conn = DBConnection.getDBConnection(); if (DCAppResponse.length() == 0) { setEvalationSessionCompleted("Data Collection Failed"); return; } Recording res = gson.fromJson(DCAppResponse, Recording.class); if (res.getFrameCount() <= 0) { // error collecting data setEvalationSessionCompleted("Data Collection Failed"); return; } if (request.requestType == request.REQUEST_TYPE_TEST) { setEvalationSessionCompleted("Test Session Only. No Recording"); return; } conn.setAutoCommit(false); // update the frame count in the session this.updateSessionWithFrameNumber(res.getFrameCount()); if (res.getSkeletonSequence() != null) { for (SkeletonSequence seq : res.getSkeletonSequence()) { this.putFrameInDB(seq); } } setEvalationSessionCompleted("Evaluation data recording complete"); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (st != null) { st.close(); } } catch (SQLException se2) { } // nothing we can do try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } //end finally try } }
From source file:edu.lternet.pasta.client.LoginClient.java
/** * Create an new LoginService object with the user's credentials and, if the * user's authentication is successful, place the user's authentication token * into the "tokenstore" for future use. * //w w w.ja v a2 s . co m * @param uid * The user identifier. * @param password * The user password. * * @throws PastaAuthenticationException */ public LoginClient(String uid, String password) throws PastaAuthenticationException { Configuration options = ConfigurationListener.getOptions(); this.pastaHost = options.getString("pasta.hostname"); this.pastaProtocol = options.getString("pasta.protocol"); this.pastaPort = options.getInt("pasta.port"); String pastaUrl = PastaClient.composePastaUrl(this.pastaProtocol, this.pastaHost, this.pastaPort); this.LOGIN_URL = pastaUrl + "/package/"; String token = this.login(uid, password); if (token == null) { String gripe = "User '" + uid + "' did not successfully authenticate."; throw new PastaAuthenticationException(gripe); } else { TokenManager tokenManager = new TokenManager(); try { tokenManager.setToken(uid, token); } catch (SQLException e) { logger.error(e); e.printStackTrace(); } catch (ClassNotFoundException e) { logger.error(e); e.printStackTrace(); } } }
From source file:desktopsearch.ExploreFiles.java
private void UpdateIndexingProgress(Integer UpdateAttribute) { try {/*from w w w . ja v a 2 s . c o m*/ String Query = "UPDATE IndexingInfo SET "; if (UpdateAttribute.equals(FileWritingFinishedIndicator)) { Query = Query + "IsFileWritingComplete=1 WHERE IndexID IN (SELECT max(IndexID) AS MaxID FROM IndexingInfo);"; } else if (UpdateAttribute.equals(IndexingFinishedIndicator)) { Query = Query + "IsIndexingComplete=1 WHERE IndexID IN (SELECT max(IndexID) AS MaxID FROM IndexingInfo) ;"; } statement.executeUpdate(Query); connection.commit(); } catch (SQLException e) { e.printStackTrace(); } }
From source file:at.alladin.rmbt.controlServer.QualityOfServiceExportResource.java
@Get public Representation request(final String entity) { //Before doing anything => check if a cached file already exists and is new enough String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); final File generatingFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); if (cachedFile.exists()) { //check if file has been recently created OR a file is currently being created if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime()) || (generatingFile.exists() && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) { //if so, return the cached file instead of a cost-intensive new one final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override/* w w w . j a v a2 s . co m*/ public void write(OutputStream out) throws IOException { InputStream is = new FileInputStream(cachedFile); IOUtils.copy(is, out); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; } } //final List<String> data = new ArrayList<String>(); final StringBuilder sb = new StringBuilder(); QoSTestObjectiveDao nnObjectiveDao = new QoSTestObjectiveDao(conn); QoSTestDescDao nnDescDao = new QoSTestDescDao(conn, null); try { Map<String, List<QoSTestObjective>> map = nnObjectiveDao.getAllToMap(); Iterator<String> keys = map.keySet().iterator(); sb.append("<h1>Contents:</h1>"); sb.append("<ol>"); sb.append("<li><a href=\"#table1\">qos_test_objective</a></li>"); sb.append("<li><a href=\"#table2\">qos_test_desc</a></li>"); sb.append("</ol><br>"); sb.append("<h1 id=\"table1\">Test objectives table (qos_test_objective)</h1>"); while (keys.hasNext()) { String testType = keys.next(); List<QoSTestObjective> list = map.get(testType); sb.append("<h2>Test group: " + testType.toUpperCase() + "</h2><ul>"); //data.add("<h2>Test group: " + testType.toUpperCase() + "</h2>"); for (QoSTestObjective item : list) { //data.add(item.toHtml()); sb.append("<li>"); sb.append(item.toHtml()); sb.append("</li>"); } sb.append("</ul>"); } Map<String, List<QoSTestDesc>> descMap = nnDescDao.getAllToMapIgnoreLang(); keys = descMap.keySet().iterator(); sb.append("<h1 id=\"table2\">Language table (qos_test_desc)</h1><ul>"); while (keys.hasNext()) { String descKey = keys.next(); List<QoSTestDesc> list = descMap.get(descKey); sb.append("<li><h4 id=\"" + descKey.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">KEY (column: desc_key): <i>" + descKey + "</i></h4><ul>"); //data.add("<h3>KEY: <i>" + descKey + "</i></h3><ul>"); for (QoSTestDesc item : list) { sb.append("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); //data.add("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); } sb.append("</ul></li>"); //data.add("</ul>"); } sb.append("</ul>"); } catch (final SQLException e) { e.printStackTrace(); return null; } final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override public void write(OutputStream out) throws IOException { //cache in file => create temporary temporary file (to // handle errors while fulfilling a request) String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); OutputStream outf = new FileOutputStream(cachedFile); if (zip) { final ZipOutputStream zos = new ZipOutputStream(outf); final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt"); zos.putNextEntry(zeLicense); final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt"); IOUtils.copy(licenseIS, zos); licenseIS.close(); final ZipEntry zeCsv = new ZipEntry(FILENAME_HTML); zos.putNextEntry(zeCsv); outf = zos; } try (OutputStreamWriter osw = new OutputStreamWriter(outf)) { osw.write(sb.toString()); osw.flush(); } if (zip) outf.close(); //if we reach this code, the data is now cached in a temporary tmp-file //so, rename the file for "production use2 //concurrency issues should be solved by the operating system File newCacheFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileInputStream fis = new FileInputStream(newCacheFile); IOUtils.copy(fis, out); fis.close(); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; }
From source file:edu.lternet.pasta.dml.database.SimpleDatabaseLoader.java
/** * Constructor of this class. Sets up the necessary components for loading data * //from ww w . ja va 2 s. co m * @param dbAdapter * Database adapter name * @param entity * Metadata information associated with the loader * @param dataReader * the data for the loader */ public SimpleDatabaseLoader(String databaseAdapterName, Entity entity, TextDataReader dataReader) { //the description this.entity = entity; //the data this.dataReader = dataReader; /* Initialize the databaseAdapter and tableMonitor fields */ this.databaseAdapter = DataManager.getDatabaseAdapterObject(databaseAdapterName); try { tableMonitor = new TableMonitor(databaseAdapter); } catch (SQLException e) { log.error("problem setting table monitor: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.mycompany.demos.Servlet3a.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .ja v a 2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; final String DB_URL = "jdbc:mysql://localhost:3306/garbagecollectionv2"; final String USER = "root"; final String PASS = "1234"; double lat = 0, lng = 0; float fullness = 0; int locationId, binId, depotId, numOfVehicles; JSONObject bins, feature, properties, geometry; JSONArray features, coordinates; features = new JSONArray(); Connection conn = null; Statement stmt = null; try { //STEP 2: Register JDBC driver System.out.println("Loading Driver..."); Class.forName(JDBC_DRIVER); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM bins inner join locations on bins.locationId = locations.locationId;"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { lat = rs.getDouble("lat"); lng = rs.getDouble("lng"); fullness = rs.getFloat("fullness"); locationId = rs.getInt("locationId"); binId = rs.getInt("binId"); //System.out.println(fullness); coordinates = new JSONArray(); coordinates.add(lng); coordinates.add(lat); geometry = new JSONObject(); geometry.put("type", "Point"); geometry.put("coordinates", coordinates); properties = new JSONObject(); properties.put("locationId", locationId); properties.put("binId", binId); properties.put("fullness", fullness); properties.put("type", "bin"); feature = new JSONObject(); feature.put("type", "Feature"); feature.put("geometry", geometry); feature.put("properties", properties); features.add(feature); } sql = "SELECT * FROM depots inner join locations on depots.locationId = locations.locationId;"; rs = stmt.executeQuery(sql); while (rs.next()) { lat = rs.getDouble("lat"); lng = rs.getDouble("lng"); numOfVehicles = rs.getInt("numOfVehicles"); locationId = rs.getInt("locationId"); depotId = rs.getInt("depotId"); //System.out.println(fullness); coordinates = new JSONArray(); coordinates.add(lng); coordinates.add(lat); geometry = new JSONObject(); geometry.put("type", "Point"); geometry.put("coordinates", coordinates); properties = new JSONObject(); properties.put("locationId", locationId); properties.put("numOfVehicles", numOfVehicles); properties.put("depotId", depotId); properties.put("type", "depot"); feature = new JSONObject(); feature.put("type", "Feature"); feature.put("geometry", geometry); feature.put("properties", properties); features.add(feature); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } } bins = new JSONObject(); bins.put("type", "FeatureCollection"); bins.put("features", features); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(bins.toString()); System.out.println(bins.toString()); }
From source file:com.drevelopment.couponcodes.bukkit.coupon.BukkitCouponHandler.java
@Override public Coupon getBasicCoupon(String coupon) { try {/*from w w w. j ava2 s. co m*/ ResultSet rs = databaseHandler.query("SELECT * FROM couponcodes WHERE name='" + coupon + "'"); if (rs == null) return null; if (databaseHandler.getDatabaseOptions() instanceof MySQLOptions) rs.first(); int usetimes = rs.getInt("usetimes"); int time = rs.getInt("timeuse"); String type = rs.getString("ctype"); if (type.equalsIgnoreCase("Item")) return createNewItemCoupon(coupon, usetimes, time, null, null); else if (type.equalsIgnoreCase("Economy")) return createNewEconomyCoupon(coupon, usetimes, time, null, 0); else if (type.equalsIgnoreCase("Rank")) return createNewRankCoupon(coupon, null, usetimes, time, null); else if (type.equalsIgnoreCase("Xp")) return this.createNewXpCoupon(coupon, 0, usetimes, time, null); else if (type.equalsIgnoreCase("command")) return this.createNewCommandCoupon(coupon, null, usetimes, time, null); else return null; } catch (SQLException e) { e.printStackTrace(); return null; } }
From source file:com.mapd.bench.Benchmark.java
String executeQuery(String sql, int expected, int iterations, int queryNum) { Connection conn = null;/*from w w w. ja v a 2 s . co m*/ Statement stmt = null; Long firstExecute = 0l; Long firstJdbc = 0l; Long firstIterate = 0l; DescriptiveStatistics statsExecute = new DescriptiveStatistics(); DescriptiveStatistics statsJdbc = new DescriptiveStatistics(); DescriptiveStatistics statsIterate = new DescriptiveStatistics(); DescriptiveStatistics statsTotal = new DescriptiveStatistics(); long totalTime = 0; try { //Open a connection logger.debug("Connecting to database url :" + url); conn = DriverManager.getConnection(url, iUser, iPasswd); long startTime = System.currentTimeMillis(); for (int loop = 0; loop < iterations; loop++) { //Execute a query stmt = conn.createStatement(); long timer = System.currentTimeMillis(); ResultSet rs = stmt.executeQuery(sql); long executeTime = 0; long jdbcTime = 0; // gather internal execute time for MapD as we are interested in that if (driver.equals(JDBC_DRIVER)) { executeTime = stmt.getQueryTimeout(); jdbcTime = (System.currentTimeMillis() - timer) - executeTime; } else { jdbcTime = (System.currentTimeMillis() - timer); executeTime = 0; } // this is fake to get our intenal execute time. logger.debug("Query Timeout/AKA internal Execution Time was " + stmt.getQueryTimeout() + " ms Elapsed time in JVM space was " + (System.currentTimeMillis() - timer) + "ms"); timer = System.currentTimeMillis(); //Extract data from result set int resultCount = 0; while (rs.next()) { Object obj = rs.getObject(1); if (obj != null && obj.equals(statsExecute)) { logger.info("Impossible"); } resultCount++; } long iterateTime = (System.currentTimeMillis() - timer); if (resultCount != expected) { logger.error("Expect " + expected + " actual " + resultCount + " for query " + sql); // don't run anymore break; } if (loop == 0) { firstJdbc = jdbcTime; firstExecute = executeTime; firstIterate = iterateTime; } else { statsJdbc.addValue(jdbcTime); statsExecute.addValue(executeTime); statsIterate.addValue(iterateTime); statsTotal.addValue(jdbcTime + executeTime + iterateTime); } //Clean-up environment rs.close(); stmt.close(); } totalTime = System.currentTimeMillis() - startTime; conn.close(); } catch (SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { //finally block used to close resources try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } // nothing we can do try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } //end finally try } //end try return String.format(lineDescriptor, queryNum, statsTotal.getMean(), statsTotal.getMin(), statsTotal.getMax(), statsTotal.getPercentile(85), statsExecute.getMean(), statsExecute.getMin(), statsExecute.getMax(), statsExecute.getPercentile(85), statsExecute.getPercentile(25), statsExecute.getStandardDeviation(), statsJdbc.getMean(), statsJdbc.getMin(), statsJdbc.getMax(), statsJdbc.getPercentile(85), statsIterate.getMean(), statsIterate.getMin(), statsIterate.getMax(), statsIterate.getPercentile(85), firstExecute, firstJdbc, firstIterate, iterations, totalTime, (long) statsTotal.getSum() + firstExecute + firstJdbc + firstIterate); }