List of usage examples for java.sql SQLException toString
public String toString()
From source file:io.github.retz.db.Database.java
public List<User> allUsers() throws IOException { List<User> ret = new LinkedList<>(); //try (Connection conn = DriverManager.getConnection(databaseURL)) { //try (Connection conn = pool.getConnection(); try (Connection conn = dataSource.getConnection(); //pool.getConnection()) { PreparedStatement p = conn.prepareStatement("SELECT * FROM users")) { conn.setAutoCommit(true);//from w w w . ja v a 2 s .c om try (ResultSet res = p.executeQuery()) { while (res.next()) { User u = MAPPER.readValue(res.getString("json"), User.class); ret.add(u); } } } catch (SQLException e) { LOG.error(e.toString()); e.printStackTrace(); } return ret; }
From source file:io.github.retz.db.Database.java
public Optional<Job> getJob(int id) throws JsonProcessingException, IOException { try (Connection conn = dataSource.getConnection(); //pool.getConnection(); PreparedStatement p = conn.prepareStatement("SELECT * FROM jobs WHERE id = ?")) { conn.setAutoCommit(true);//from w w w . j av a2 s .com p.setInt(1, id); try (ResultSet res = p.executeQuery()) { if (res.next()) { String json = res.getString("json"); Job job = MAPPER.readValue(json, Job.class); if (id != job.id()) { LOG.error("{} != {} in Database", id, job.id()); throw new AssertionError("id in JSON must be equal to the column"); } return Optional.of(job); } // No such application } } catch (SQLException e) { LOG.error(e.toString()); } return Optional.empty(); }
From source file:io.github.retz.db.Database.java
public Optional<Job> getJobFromTaskId(String taskId) throws JsonProcessingException, IOException { try (Connection conn = dataSource.getConnection(); //pool.getConnection(); PreparedStatement p = conn.prepareStatement("SELECT json FROM jobs WHERE taskid=?")) { conn.setAutoCommit(true);// ww w .j a v a2s. c o m p.setString(1, taskId); try (ResultSet res = p.executeQuery()) { if (res.next()) { String json = res.getString("json"); Job job = MAPPER.readValue(json, Job.class); if (!taskId.equals(job.taskId())) { LOG.error("{} != {} in Database", taskId, job.taskId()); throw new AssertionError("id in JSON must be equal to the column"); } return Optional.of(job); } LOG.info("no such application/job"); // No such application } } catch (SQLException e) { LOG.error(e.toString()); } return Optional.empty(); }
From source file:io.github.retz.db.Database.java
public Optional<AppJobPair> getAppJob(int id) throws IOException { try (Connection conn = dataSource.getConnection(); //pool.getConnection(); PreparedStatement p = conn.prepareStatement( "SELECT j.json, a.json FROM jobs j, applications a WHERE id = ? AND j.appid = a.appid")) { conn.setAutoCommit(true);//www . j a v a 2s . c o m p.setInt(1, id); try (ResultSet res = p.executeQuery()) { if (res.next()) { String jjson = res.getString(1); Job job = MAPPER.readValue(jjson, Job.class); if (id != job.id()) { LOG.error("{} != {} in Database", id, job.id()); throw new AssertionError("id in JSON must be equal to the column"); } String ajson = res.getString(2); Application app = MAPPER.readValue(ajson, Application.class); return Optional.of(new AppJobPair(Optional.of(app), job)); } // No such application } } catch (SQLException e) { LOG.error(e.toString()); } return Optional.empty(); }
From source file:io.github.retz.db.Database.java
List<Job> getAllJobs(String id) throws IOException { List<Job> ret = new LinkedList<>(); String sql = "SELECT j.json FROM jobs j"; if (id != null) { sql = "SELECT j.json FROM jobs j, applications a WHERE j.appid = a.appid AND a.owner = ?"; }/*from ww w. j ava 2s. co m*/ try (Connection conn = dataSource.getConnection(); // pool.getConnection(); PreparedStatement p = conn.prepareStatement(sql)) { if (id != null) { p.setString(1, id); } conn.setAutoCommit(true); try (ResultSet res = p.executeQuery()) { while (res.next()) { //String json = res.getString("j.json"); String json = res.getString(1); Job job = MAPPER.readValue(json, Job.class); ret.add(job); } } } catch (SQLException e) { LOG.error(e.toString()); e.printStackTrace(); } return ret; }
From source file:io.github.retz.db.Database.java
public boolean addApplication(Application a) throws IOException { try (Connection conn = dataSource.getConnection(); //pool.getConnection(); PreparedStatement p = conn .prepareStatement("INSERT INTO applications(appid, owner, json) values(?, ?, ?)")) { conn.setAutoCommit(false);//from w w w. j a v a 2 s . c o m Optional<User> u = getUser(conn, a.getOwner()); if (!u.isPresent()) { LOG.warn("{} tried to load application {}, but the user not present", a.getOwner(), a.getAppid()); return false; } else if (!u.get().enabled()) { LOG.warn("{} tried to load application {}, but user.enabled={}", a.getOwner(), a.getAppid(), u.get().enabled()); return false; } deleteApplication(conn, a.getAppid()); p.setString(1, a.getAppid()); p.setString(2, a.getOwner()); p.setString(3, MAPPER.writeValueAsString(a)); p.execute(); conn.commit(); return true; } catch (SQLException e) { LOG.error(e.toString()); e.printStackTrace(); return false; } }
From source file:edu.indiana.d2i.komadu.query.db.BaseDBQuerier.java
public FindActivityResponseDocument findActivity(Connection connection, FindActivityRequestType findActivityRequestType) throws QueryException, SQLException { l.debug("Entering findActivity()"); assert (connection != null); assert (findActivityRequestType != null); PreparedStatement findActivityStmt = null; ResultSet res = null;/*from ww w .j a v a 2 s .co m*/ FindActivityResponseDocument findActivityResponseDocument = FindActivityResponseDocument.Factory .newInstance(); FindActivityResponseType findActivityResponseType = findActivityResponseDocument .addNewFindActivityResponse(); ActivityIDListType activityIDListType = findActivityResponseType.addNewActivityIDList(); try { StringBuilder query = new StringBuilder(); if (findActivityRequestType.isSetAttributeList()) { if (findActivityRequestType.isSetNextActivityID()) query.append(PROVSqlQuery.FIND_ACTIVITY_ATTRIBUTE_COMM); else query.append(PROVSqlQuery.FIND_ACTIVITY_ATTRIBUTE); } else { if (findActivityRequestType.isSetNextActivityID()) query.append(PROVSqlQuery.FIND_ACTIVITY_COMM); else query.append(PROVSqlQuery.FIND_ACTIVITY); } String nextActivity = findActivityRequestType.getNextActivityID(); String nextActivityID; if (nextActivity != null) { PreparedStatement findNextActivityStmt; if (nextActivity.startsWith(QueryConstants.ACTIVITY_IDENTIFIER)) { // if the activity id is provided nextActivity = nextActivity.replace(QueryConstants.ACTIVITY_IDENTIFIER, ""); findNextActivityStmt = connection.prepareStatement(PROVSqlQuery.GET_ACTIVITY_BY_ID); } else { // there the uri is provided findNextActivityStmt = connection.prepareStatement(PROVSqlQuery.GET_ACTIVITY_BY_URI); } findNextActivityStmt.setString(1, nextActivity); ResultSet nextActivityRes = findNextActivityStmt.executeQuery(); int nextActivityCount = 0; if (nextActivityRes.next()) { nextActivityID = nextActivityRes.getString(1); query.append("AND c.informed_id = '").append(nextActivityID).append("' "); nextActivityCount++; } nextActivityRes.close(); findNextActivityStmt.close(); if (nextActivityCount == 0) { l.info("No activity with specified next activity found."); l.debug("Exiting findActivity() with success."); return findActivityResponseDocument; } } String architecture = findActivityRequestType.getArchitecture(); String hostName = findActivityRequestType.getHostName(); String name = findActivityRequestType.getName(); String workflowID = findActivityRequestType.getWorkflowID(); String serviceID = findActivityRequestType.getServiceID(); // Calendar initializationTime = findActivityRequestType.getInitializationTime(); // Calendar terminationTime = findActivityRequestType.getTerminationTime(); // boolean isSuccess = findActivityRequestType.getIsSuccess(); AttributesType attributeList = findActivityRequestType.getAttributeList(); if (findActivityRequestType.isSetArchitecture()) query.append("AND a.activity_uri LIKE '%").append(architecture).append("%' "); if (findActivityRequestType.isSetHostName()) query.append("AND a.activity_uri LIKE '%").append(hostName).append("%' "); if (findActivityRequestType.isSetName()) query.append("AND a.activity_uri LIKE '%").append(name).append("%' "); if (findActivityRequestType.isSetWorkflowID()) query.append("AND a.context_workflow_uri LIKE '%").append(workflowID).append("%' "); if (findActivityRequestType.isSetServiceID()) query.append("AND a.context_service_uri LIKE '%").append(serviceID).append("%' "); // TODO : Add invocation time, termination time and status into communication? // if (findActivityRequestType.isSetInitializationTime()) // query.append("AND i.invocation_start_time LIKE '%").append(initializationTime).append("%' "); // if (findActivityRequestType.isSetTerminationTime()) // query.append("AND i.execution_end_time LIKE '%").append(terminationTime).append("%' "); // // // default to SUCCESS if not specified // l.debug("isSetIsSuccess: " + findActivityRequestType.isSetIsSuccess()); // if (!findActivityRequestType.isSetIsSuccess()) // query.append("AND i.execution_status = '" // + StatusEnum.SUCCESS.toString() + "' "); // else if (isSuccess) // query.append("AND i.execution_status = '" // + StatusEnum.SUCCESS.toString() + "' "); // else // query.append("AND i.execution_status = '" // + StatusEnum.FAILED.toString() + "' "); if (findActivityRequestType.isSetAttributeList()) { for (int i = 0; i < attributeList.sizeOfAttributeArray(); i++) { query.append(PROVSqlQuery.ATTRIBUTE_COMPARISON); } } findActivityStmt = connection.prepareStatement(query.toString()); l.debug("findActivityStmt: " + findActivityStmt); if (findActivityRequestType.isSetAttributeList()) { for (int i = 1; i <= attributeList.sizeOfAttributeArray(); i++) { findActivityStmt.setString(i, '%' + findActivityRequestType.getAttributeList().getAttributeArray(i).getValue() + '%'); } } res = findActivityStmt.executeQuery(); while (res.next()) { XmlString activityID = activityIDListType.addNewActivityID(); activityID.setStringValue(res.getString("activity_uri")); } res.close(); findActivityStmt.close(); } catch (SQLException e) { l.error("Exiting findActivity() with SQL errors."); l.error(e.toString()); return null; } finally { if (findActivityStmt != null) { findActivityStmt.close(); } if (res != null) { res.close(); } } l.debug("Response: " + findActivityResponseDocument); l.debug("Exiting findActivity() with success."); return findActivityResponseDocument; }
From source file:io.github.retz.db.Database.java
public List<Job> findFit(List<String> orderBy, int cpu, int memMB) throws IOException { List<Job> ret = new LinkedList<>(); String orders = String.join(", ", orderBy.stream().map(s -> s + " ASC").collect(Collectors.toList())); try (Connection conn = dataSource.getConnection(); //pool.getConnection(); PreparedStatement p = conn .prepareStatement("SELECT * FROM jobs WHERE state='QUEUED' ORDER BY " + orders)) { conn.setAutoCommit(true);/*from ww w . j ava 2s. co m*/ try (ResultSet res = p.executeQuery()) { int totalCpu = 0; int totalMem = 0; while (res.next() && totalCpu <= cpu && totalMem <= memMB) { String json = res.getString("json"); Job job = MAPPER.readValue(json, Job.class); if (job == null) { throw new AssertionError("Cannot be null!!"); } else if (totalCpu + job.resources().getCpu() <= cpu && totalMem + job.resources().getMemMB() <= memMB) { ret.add(job); totalCpu += job.resources().getCpu(); totalMem += job.resources().getMemMB(); } else { break; } } } } catch (SQLException e) { LOG.error(e.toString()); e.printStackTrace(); } return ret; }
From source file:org.apache.torque.task.TorqueSQLExec.java
/** * Exec the sql statement./*from w w w.jav a2s .com*/ * * @param sql * @param out * @throws SQLException */ protected void execSQL(String sql, PrintStream out) throws SQLException { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } try { totalSql++; if (!statement.execute(sql)) { log(statement.getUpdateCount() + " rows affected", Project.MSG_VERBOSE); } else { if (print) { printResults(out); } } SQLWarning warning = conn.getWarnings(); while (warning != null) { log(warning + " sql warning", Project.MSG_VERBOSE); warning = warning.getNextWarning(); } conn.clearWarnings(); goodSql++; } catch (SQLException e) { System.out.println("Failed to execute: " + sql); if (!onError.equals("continue")) { throw e; } log(e.toString(), Project.MSG_ERR); } }
From source file:at.alladin.rmbt.controlServer.IpResource.java
@Post("json") public String request(final String entity) { addAllowOrigin();//from ww w . j av a 2 s . co m JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); final InetAddress clientAddress = InetAddresses.forString(clientIpRaw); System.out.println(MessageFormat.format(labels.getString("NEW_IP_REQ"), clientIpRaw)); if (entity != null && !entity.isEmpty()) { // try parse the string to a JSON object try { // debug parameters sent request = new JSONObject(entity); System.out.println(request.toString(4)); /* sample request data { "api_level": "21", "device": "hammerhead", "language": "en", "model": "Nexus 5", "os_version": "5.0(1570415)", "plattform": "Android", "product": "hammerhead", "softwareRevision": "master_initial-2413-gf89049d", "softwareVersionCode": 20046, "softwareVersionName": "2.0.46", "timezone": "Europe/Vienna", "type": "MOBILE", "uuid": "........(uuid)........" "location": { "accuracy": 20, "age": 7740, "lat": 51.1053539, "long": 17.4921002, "provider": "network" }, } */ UUID uuid = null; final String uuidString = request.optString("uuid", ""); if (uuidString.length() != 0) uuid = UUID.fromString(uuidString); final String clientPlattform = request.getString("plattform"); final String clientModel = request.getString("model"); final String clientProduct = request.getString("product"); final String clientDevice = request.getString("device"); final String clientSoftwareVersionCode = request.getString("softwareVersionCode"); final String clientApiLevel = request.getString("api_level"); final JSONObject location = request.optJSONObject("location"); long geoage = 0; // age in ms double geolat = 0; double geolong = 0; float geoaccuracy = 0; // in m double geoaltitude = 0; float geospeed = 0; // in m/s String geoprovider = ""; if (!request.isNull("location")) { geoage = location.optLong("age", 0); geolat = location.optDouble("lat", 0); geolong = location.optDouble("long", 0); geoaccuracy = (float) location.optDouble("accuracy", 0); geoaltitude = location.optDouble("altitude", 0); geospeed = (float) location.optDouble("speed", 0); geoprovider = location.optString("provider", ""); } if (errorList.getLength() == 0) try { PreparedStatement st; st = conn.prepareStatement( "INSERT INTO status(client_uuid,time,plattform,model,product,device,software_version_code,api_level,ip," + "age,lat,long,accuracy,altitude,speed,provider)" + "VALUES(?, NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); int i = 1; st.setObject(i++, uuid); st.setObject(i++, clientPlattform); st.setObject(i++, clientModel); st.setObject(i++, clientProduct); st.setObject(i++, clientDevice); st.setObject(i++, clientSoftwareVersionCode); st.setObject(i++, clientApiLevel); st.setObject(i++, clientIpRaw); // location information st.setObject(i++, geoage); st.setObject(i++, geolat); st.setObject(i++, geolong); st.setObject(i++, geoaccuracy); st.setObject(i++, geoaltitude); st.setObject(i++, geospeed); st.setObject(i++, geoprovider); final int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_STORE_STATUS"); } catch (final SQLException e) { errorList.addError("ERROR_DB_STORE_GENERAL"); e.printStackTrace(); } answer.put("ip", clientIpRaw); if (clientAddress instanceof Inet4Address) { answer.put("v", "4"); } else if (clientAddress instanceof Inet6Address) { answer.put("v", "6"); } else { answer.put("v", "0"); } } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSON Data " + e.toString()); } } else { errorList.addErrorString("Expected request is missing."); } try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); return answerString; }