193 lines
10 KiB
HTML
193 lines
10 KiB
HTML
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="de"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>DBService.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">backend</a> > <a href="index.source.html" class="el_package">com.workbenchclassic</a> > <span class="el_source">DBService.java</span></div><h1>DBService.java</h1><pre class="source lang-java linenums">package com.workbenchclassic;
|
|
|
|
import java.sql.*;
|
|
import java.util.*;
|
|
import java.util.logging.Level;
|
|
import java.util.logging.Logger;
|
|
import javax.naming.InitialContext;
|
|
import javax.naming.NamingException;
|
|
import javax.sql.DataSource;
|
|
import org.json.JSONArray;
|
|
import org.json.JSONObject;
|
|
|
|
/**
|
|
* DBService handles database connections, queries, and results.
|
|
*/
|
|
public class DBService {
|
|
|
|
/** Logger for this class. */
|
|
<span class="nc" id="L19"> private static final Logger LOGGER = Logger.getLogger(DBService.class.getName());</span>
|
|
private String dataSourceName; // Make DATASOURCE_NAME an instance variable
|
|
|
|
/**
|
|
* Constructor to set the DataSource name.
|
|
*
|
|
* @param dataSourceName The name of the DataSource.
|
|
*/
|
|
<span class="nc" id="L27"> public DBService(String dataSourceName) {</span>
|
|
<span class="nc" id="L28"> this.dataSourceName = dataSourceName;</span>
|
|
<span class="nc" id="L29"> }</span>
|
|
|
|
/**
|
|
* Connects to the database and executes a query.
|
|
*
|
|
* @param query The SQL statement.
|
|
* @return JSON response with results or error.
|
|
*/
|
|
public String dbConnect(String query) {
|
|
<span class="nc" id="L38"> try (Connection connection = getConnection();</span>
|
|
<span class="nc" id="L39"> Statement statement = connection.createStatement()) {</span>
|
|
|
|
<span class="nc bnc" id="L41" title="All 2 branches missed."> return isSelectQuery(query) ? executeSelect(statement, query) : executeUpdate(statement, query);</span>
|
|
|
|
<span class="nc" id="L43"> } catch (SQLException e) {</span>
|
|
<span class="nc" id="L44"> return handleSQLException("SQL error", e);</span>
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetches rows from the database as a list of maps.
|
|
*
|
|
* @param query The SQL SELECT query.
|
|
* @return List of rows with column names as keys.
|
|
* @throws SQLException if a database error occurs.
|
|
*/
|
|
public List<Map<String, Object>> dbConnectAndGetRows(String query) throws SQLException {
|
|
<span class="nc" id="L56"> List<Map<String, Object>> results = new ArrayList<>();</span>
|
|
|
|
<span class="nc" id="L58"> try (Connection connection = getConnection();</span>
|
|
<span class="nc" id="L59"> Statement statement = connection.createStatement();</span>
|
|
<span class="nc" id="L60"> ResultSet rs = statement.executeQuery(query)) {</span>
|
|
|
|
<span class="nc" id="L62"> processResultSet(rs, results);</span>
|
|
|
|
<span class="nc" id="L64"> } catch (SQLException sqle) {</span>
|
|
<span class="nc" id="L65"> LOGGER.log(Level.SEVERE, "SQL error in dbConnectAndGetRows", sqle);</span>
|
|
<span class="nc" id="L66"> throw sqle;</span>
|
|
<span class="nc" id="L67"> }</span>
|
|
<span class="nc" id="L68"> return results;</span>
|
|
}
|
|
|
|
public List<Map<String, Object>> preparedDbConnectAndGetRows(PreparedStatement ps) throws SQLException {
|
|
<span class="nc" id="L72"> List<Map<String, Object>> results = new ArrayList<>();</span>
|
|
|
|
<span class="nc" id="L74"> try (ResultSet rs = ps.executeQuery()) {</span>
|
|
<span class="nc" id="L75"> processResultSet(rs, results);</span>
|
|
<span class="nc" id="L76"> } catch (SQLException sqle) {</span>
|
|
<span class="nc" id="L77"> LOGGER.log(Level.SEVERE, "SQL error in dbConnectAndGetRows(PreparedStatement)", sqle);</span>
|
|
<span class="nc" id="L78"> throw sqle;</span>
|
|
<span class="nc" id="L79"> }</span>
|
|
<span class="nc" id="L80"> return results;</span>
|
|
}
|
|
|
|
/**
|
|
* Executes a SELECT query and formats the result as JSON.
|
|
*/
|
|
private String executeSelect(Statement statement, String query) throws SQLException {
|
|
<span class="nc" id="L87"> JSONArray rows = new JSONArray();</span>
|
|
<span class="nc" id="L88"> try (ResultSet rs = statement.executeQuery(query)) {</span>
|
|
<span class="nc" id="L89"> processResultSet(rs, rows);</span>
|
|
}
|
|
<span class="nc" id="L91"> return getJsonResponse("0", "Success", rows.toString());</span>
|
|
}
|
|
|
|
/**
|
|
* Executes an UPDATE/INSERT/DELETE query.
|
|
*/
|
|
private String executeUpdate(Statement statement, String query) throws SQLException {
|
|
<span class="nc" id="L98"> int resultCount = statement.executeUpdate(query);</span>
|
|
<span class="nc" id="L99"> JSONArray updateResult = new JSONArray();</span>
|
|
<span class="nc" id="L100"> updateResult.put("Result");</span>
|
|
<span class="nc" id="L101"> updateResult.put(resultCount);</span>
|
|
<span class="nc" id="L102"> return getJsonResponse("0", "Done", updateResult.toString());</span>
|
|
}
|
|
|
|
/**
|
|
* Processes the ResultSet and stores rows into a JSON array.
|
|
*/
|
|
private void processResultSet(ResultSet rs, JSONArray rows) throws SQLException {
|
|
<span class="nc" id="L109"> ResultSetMetaData metaData = rs.getMetaData();</span>
|
|
<span class="nc" id="L110"> int columnCount = metaData.getColumnCount();</span>
|
|
|
|
<span class="nc bnc" id="L112" title="All 2 branches missed."> while (rs.next()) {</span>
|
|
<span class="nc" id="L113"> JSONObject row = new JSONObject();</span>
|
|
<span class="nc bnc" id="L114" title="All 2 branches missed."> for (int i = 1; i <= columnCount; i++) {</span>
|
|
<span class="nc" id="L115"> row.put(metaData.getColumnLabel(i).toLowerCase(), rs.getObject(i));</span>
|
|
}
|
|
<span class="nc" id="L117"> rows.put(row);</span>
|
|
<span class="nc" id="L118"> }</span>
|
|
<span class="nc" id="L119"> }</span>
|
|
|
|
/**
|
|
* Processes the ResultSet and stores rows into a List of Maps.
|
|
*/
|
|
private void processResultSet(ResultSet rs, List<Map<String, Object>> results) throws SQLException {
|
|
<span class="nc" id="L125"> ResultSetMetaData metaData = rs.getMetaData();</span>
|
|
<span class="nc" id="L126"> int columnCount = metaData.getColumnCount();</span>
|
|
|
|
<span class="nc bnc" id="L128" title="All 2 branches missed."> while (rs.next()) {</span>
|
|
<span class="nc" id="L129"> Map<String, Object> rowMap = new HashMap<>();</span>
|
|
<span class="nc bnc" id="L130" title="All 2 branches missed."> for (int i = 1; i <= columnCount; i++) {</span>
|
|
<span class="nc" id="L131"> rowMap.put(metaData.getColumnLabel(i).toLowerCase(), rs.getObject(i));</span>
|
|
}
|
|
<span class="nc" id="L133"> results.add(rowMap);</span>
|
|
<span class="nc" id="L134"> }</span>
|
|
<span class="nc" id="L135"> }</span>
|
|
|
|
/**
|
|
* Determines if the query is a SELECT statement.
|
|
*/
|
|
private boolean isSelectQuery(String query) {
|
|
<span class="nc bnc" id="L141" title="All 4 branches missed."> return query != null && query.trim().toLowerCase().startsWith("select");</span>
|
|
}
|
|
|
|
/**
|
|
* Handles SQL exceptions and logs errors.
|
|
*/
|
|
private String handleSQLException(String message, SQLException e) {
|
|
<span class="nc" id="L148"> LOGGER.log(Level.SEVERE, message + ": " + e.getMessage(), e);</span>
|
|
<span class="nc" id="L149"> return getJsonResponse("-999", message, e.getMessage());</span>
|
|
}
|
|
|
|
/**
|
|
* Retrieves database product name.
|
|
*/
|
|
public String getDatabaseProductName() {
|
|
<span class="nc" id="L156"> try (Connection connection = getConnection()) {</span>
|
|
<span class="nc" id="L157"> return connection.getMetaData().getDatabaseProductName();</span>
|
|
<span class="nc" id="L158"> } catch (SQLException e) {</span>
|
|
<span class="nc" id="L159"> return handleSQLException("Database error", e);</span>
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Retrieves a DataSource via JNDI lookup.
|
|
*/
|
|
private DataSource lookupDataSource(String dataSourceName) throws NamingException {
|
|
<span class="nc" id="L167"> InitialContext ctx = new InitialContext();</span>
|
|
<span class="nc" id="L168"> return (DataSource) ctx.lookup(dataSourceName); // Corrected JNDI lookup</span>
|
|
}
|
|
|
|
/**
|
|
* Retrieves a database connection.
|
|
*/
|
|
public Connection getConnection() throws SQLException {
|
|
try {
|
|
<span class="nc" id="L176"> return lookupDataSource(dataSourceName).getConnection();</span>
|
|
<span class="nc" id="L177"> } catch (NamingException ne) {</span>
|
|
<span class="nc" id="L178"> throw new SQLException("JNDI NamingException occurred while getting connection", ne);</span>
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Builds a JSON response.
|
|
*/
|
|
private String getJsonResponse(String errorCode, String errorMessage, String data) {
|
|
<span class="nc" id="L186"> JSONObject obj = new JSONObject();</span>
|
|
<span class="nc" id="L187"> obj.put("errorCode", errorCode);</span>
|
|
<span class="nc" id="L188"> obj.put("errorMessage", errorMessage);</span>
|
|
<span class="nc" id="L189"> obj.put("data", data);</span>
|
|
<span class="nc" id="L190"> return obj.toString();</span>
|
|
}
|
|
}
|
|
</pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.4.201905082037</span></div></body></html> |