Search in sources :

Example 1 with Statement

use of model.Statement in project dna by leifeld.

the class Sql method getDocuments.

/**
 * Get documents for a batch of document IDs. The data can be displayed and
 * edited in a {@link gui.DocumentEditor DocumentEditor} dialog. The
 * documents do not contain any statements.
 *
 * @param documentIds    An array of document IDs for which the data should
 *   be queried.
 * @return             An {@link java.util.ArrayList ArrayList} of
 *   {@link model.Document Document} objects, containing the documents and
 *   their meta-data.
 *
 * @category document
 */
public ArrayList<Document> getDocuments(int[] documentIds) {
    ArrayList<Document> documents = new ArrayList<Document>();
    String sql = "SELECT * FROM DOCUMENTS WHERE ID IN (";
    for (int i = 0; i < documentIds.length; i++) {
        sql = sql + documentIds[i];
        if (i < documentIds.length - 1) {
            sql = sql + ", ";
        }
    }
    sql = sql + ");";
    try (Connection conn = getDataSource().getConnection();
        PreparedStatement s = conn.prepareStatement(sql)) {
        ResultSet rs = s.executeQuery();
        while (rs.next()) {
            Document d = new Document(rs.getInt("ID"), rs.getInt("Coder"), rs.getString("Title"), rs.getString("Text"), rs.getString("Author"), rs.getString("Source"), rs.getString("Section"), rs.getString("Type"), rs.getString("Notes"), LocalDateTime.ofEpochSecond(rs.getLong("Date"), 0, ZoneOffset.UTC), new ArrayList<Statement>());
            documents.add(d);
        }
    } catch (SQLException e) {
        LogEvent l = new LogEvent(Logger.WARNING, "[SQL] Failed to retrieve document meta-data from the database.", "Attempted to retrieve document data (other than the document text) for " + documentIds.length + " documents, but this failed. Check if all documents are being displayed in the user interface.", e);
        Dna.logger.log(l);
    }
    return documents;
}
Also used : SQLException(java.sql.SQLException) LogEvent(logger.LogEvent) PreparedStatement(java.sql.PreparedStatement) Statement(model.Statement) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) TableDocument(model.TableDocument) Document(model.Document)

Example 2 with Statement

use of model.Statement in project dna by leifeld.

the class Sql method getStatement.

/**
 * Get a statement from the database based on its ID.
 *
 * @param statementId  The statement ID of the statement to be retrieved.
 * @return             A {@link model.Statement Statement} with all relevant
 *   values for the different variables.
 *
 * @category statement
 */
public Statement getStatement(int statementId) {
    Statement statement = null;
    ArrayList<Value> values;
    int statementTypeId, variableId, entityId;
    String variable, dataType;
    Color aColor, sColor, cColor;
    HashMap<String, String> map;
    String subString = "SUBSTRING(DOCUMENTS.Text, Start + 1, Stop - Start) AS Text ";
    if (getConnectionProfile().getType().equals("postgresql")) {
        subString = "SUBSTRING(DOCUMENTS.Text, CAST(Start + 1 AS INT4), CAST(Stop - Start AS INT4)) AS Text ";
    }
    String s1Query = "SELECT STATEMENTS.ID AS StatementId, " + "StatementTypeId, " + "STATEMENTTYPES.Label AS StatementTypeLabel, " + "STATEMENTTYPES.Red AS StatementTypeRed, " + "STATEMENTTYPES.Green AS StatementTypeGreen, " + "STATEMENTTYPES.Blue AS StatementTypeBlue, " + "Start, " + "Stop, " + "STATEMENTS.Coder AS CoderId, " + "CODERS.Name AS CoderName, " + "CODERS.Red AS CoderRed, " + "CODERS.Green AS CoderGreen, " + "CODERS.Blue AS CoderBlue, " + "DocumentId, " + "DOCUMENTS.Date AS Date, " + subString + "FROM STATEMENTS " + "INNER JOIN CODERS ON STATEMENTS.Coder = CODERS.ID " + "INNER JOIN STATEMENTTYPES ON STATEMENTS.StatementTypeId = STATEMENTTYPES.ID " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + "WHERE STATEMENTS.ID = ?;";
    try (Connection conn = ds.getConnection();
        PreparedStatement s1 = conn.prepareStatement(s1Query);
        PreparedStatement s2 = conn.prepareStatement("SELECT ID, Variable, DataType FROM VARIABLES WHERE StatementTypeId = ?;");
        PreparedStatement s3 = conn.prepareStatement("SELECT E.ID AS EntityId, StatementId, E.VariableId, DST.ID AS DataId, E.Value, Red, Green, Blue, ChildOf FROM DATASHORTTEXT AS DST LEFT JOIN ENTITIES AS E ON E.ID = DST.Entity AND E.VariableId = DST.VariableId WHERE DST.StatementId = ? AND DST.VariableId = ?;");
        PreparedStatement s4 = conn.prepareStatement("SELECT Value FROM DATALONGTEXT WHERE VariableId = ? AND StatementId = ?;");
        PreparedStatement s5 = conn.prepareStatement("SELECT Value FROM DATAINTEGER WHERE VariableId = ? AND StatementId = ?;");
        PreparedStatement s6 = conn.prepareStatement("SELECT Value FROM DATABOOLEAN WHERE VariableId = ? AND StatementId = ?;");
        PreparedStatement s7 = conn.prepareStatement("SELECT AttributeVariable, AttributeValue FROM ATTRIBUTEVALUES AS AVAL INNER JOIN ATTRIBUTEVARIABLES AS AVAR ON AVAL.AttributeVariableId = AVAR.ID WHERE EntityId = ?;")) {
        ResultSet r1, r2, r3, r4;
        // first, get the statement information, including coder and statement type info
        s1.setInt(1, statementId);
        r1 = s1.executeQuery();
        while (r1.next()) {
            statementTypeId = r1.getInt("StatementTypeId");
            sColor = new Color(r1.getInt("StatementTypeRed"), r1.getInt("StatementTypeGreen"), r1.getInt("StatementTypeBlue"));
            cColor = new Color(r1.getInt("CoderRed"), r1.getInt("CoderGreen"), r1.getInt("CoderBlue"));
            // second, get the variables associated with the statement type
            s2.setInt(1, statementTypeId);
            r2 = s2.executeQuery();
            values = new ArrayList<Value>();
            while (r2.next()) {
                variableId = r2.getInt("ID");
                variable = r2.getString("Variable");
                dataType = r2.getString("DataType");
                // third, get the values from DATABOOLEAN, DATAINTEGER, DATALONGTEXT, and DATASHORTTEXT
                if (dataType.equals("short text")) {
                    s3.setInt(1, statementId);
                    s3.setInt(2, variableId);
                    r3 = s3.executeQuery();
                    while (r3.next()) {
                        entityId = r3.getInt("EntityId");
                        aColor = new Color(r3.getInt("Red"), r3.getInt("Green"), r3.getInt("Blue"));
                        // fourth, in the case of short text, also look up information in ENTITIES table
                        s7.setInt(1, entityId);
                        r4 = s7.executeQuery();
                        map = new HashMap<String, String>();
                        while (r4.next()) {
                            map.put(r4.getString("AttributeVariable"), r4.getString("AttributeValue"));
                        }
                        Entity entity = new Entity(entityId, variableId, r3.getString("Value"), aColor, r3.getInt("ChildOf"), true, map);
                        values.add(new Value(variableId, variable, dataType, entity));
                    }
                } else if (dataType.equals("long text")) {
                    s4.setInt(1, variableId);
                    s4.setInt(2, statementId);
                    r3 = s4.executeQuery();
                    while (r3.next()) {
                        values.add(new Value(variableId, variable, dataType, r3.getString("Value")));
                    }
                } else if (dataType.equals("integer")) {
                    s5.setInt(1, variableId);
                    s5.setInt(2, statementId);
                    r3 = s5.executeQuery();
                    while (r3.next()) {
                        values.add(new Value(variableId, variable, dataType, r3.getInt("Value")));
                    }
                } else if (dataType.equals("boolean")) {
                    s6.setInt(1, variableId);
                    s6.setInt(2, statementId);
                    r3 = s6.executeQuery();
                    while (r3.next()) {
                        values.add(new Value(variableId, variable, dataType, r3.getInt("Value")));
                    }
                }
            }
            // assemble the statement with all the information from the previous steps
            statement = new Statement(statementId, r1.getInt("Start"), r1.getInt("Stop"), statementTypeId, r1.getString("StatementTypeLabel"), sColor, r1.getInt("CoderId"), r1.getString("CoderName"), cColor, values, r1.getInt("DocumentId"), r1.getString("Text"), LocalDateTime.ofEpochSecond(r1.getLong("Date"), 0, ZoneOffset.UTC));
            LogEvent l = new LogEvent(Logger.MESSAGE, "[SQL] Statement " + statementId + " was retrieved from the database.", "Statement " + statementId + " was retrieved from the database.");
            Dna.logger.log(l);
        }
    } catch (SQLException e) {
        LogEvent l = new LogEvent(Logger.WARNING, "[SQL] Failed to retrieve Statement " + statementId + " from database.", "Failed to retrieve Statement " + statementId + " from database. Check if the connection is still there, the database file has not been moved, and make sure a statement with this ID actually exists in the database.", e);
        Dna.logger.log(l);
    }
    return statement;
}
Also used : Entity(model.Entity) LogEvent(logger.LogEvent) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(model.Statement) Color(java.awt.Color) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Value(model.Value) ResultSet(java.sql.ResultSet)

Example 3 with Statement

use of model.Statement in project dna by leifeld.

the class Sql method getStatements.

/**
 * Get statements, potentially filtered by statement IDs, document
 * meta-data, date/time range, and duplicates setting.
 *
 * @param statementIds   Array of statement IDs to retrieve. Can be empty or
 *   null, in which case all statements are selected.
 * @param startDateTime  Date/time before which statements are discarded.
 * @param stopDateTime   Date/time after which statements are discarded.
 * @param authors        Array list of document authors to exclude. Can be
 *   empty or null, in which case all statements are selected.
 * @param authorInclude  Include authors instead of excluding them?
 * @param sources        Array list of document sources to exclude. Can be
 *   empty or null, in which case all statements are selected.
 * @param sourceInclude  Include sources instead of excluding them?
 * @param sections       Array list of document sections to exclude. Can be
 *   empty or null, in which case all statements are selected.
 * @param sectionInclude Include sections instead of excluding them?
 * @param types          Array list of document types to exclude. Can be
 *   empty or null, in which case all statements are selected.
 * @param typeInclude    Include types instead of excluding them?
 * @return Array list of statements with all details.
 */
public ArrayList<Statement> getStatements(int[] statementIds, LocalDateTime startDateTime, LocalDateTime stopDateTime, ArrayList<String> authors, boolean authorInclude, ArrayList<String> sources, boolean sourceInclude, ArrayList<String> sections, boolean sectionInclude, ArrayList<String> types, boolean typeInclude) {
    String whereStatements = "";
    String whereShortText = "";
    String whereLongText = "";
    String whereBoolean = "";
    String whereInteger = "";
    if (statementIds != null && statementIds.length > 0) {
        String ids = "";
        for (int i = 0; i < statementIds.length; i++) {
            ids = ids + statementIds[i];
            if (i < statementIds.length - 1) {
                ids = ids + ", ";
            }
        }
        whereStatements = "WHERE STATEMENTS.ID IN (" + ids + ") ";
        whereShortText = "AND DATASHORTTEXT.StatementId IN (" + ids + ") ";
        whereLongText = "AND DATALONGTEXT.StatementId IN (" + ids + ") ";
        whereBoolean = "AND DATABOOLEAN.StatementId IN (" + ids + ") ";
        whereInteger = "AND DATAINTEGER.StatementId IN (" + ids + ") ";
    }
    if (startDateTime != null) {
        whereStatements = whereStatements + "AND Date >= " + startDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereShortText = whereShortText + "AND Date >= " + startDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereLongText = whereLongText + "AND Date >= " + startDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereBoolean = whereBoolean + "AND Date >= " + startDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereInteger = whereInteger + "AND Date >= " + startDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
    }
    if (stopDateTime != null) {
        whereStatements = whereStatements + "AND Date <= " + stopDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereShortText = whereShortText + "AND Date <= " + stopDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereLongText = whereLongText + "AND Date <= " + stopDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereBoolean = whereBoolean + "AND Date <= " + stopDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
        whereInteger = whereInteger + "AND Date <= " + stopDateTime.toEpochSecond(ZoneOffset.UTC) + " ";
    }
    if (authors != null && authors.size() > 0) {
        String authorNot = "";
        if (!authorInclude) {
            authorNot = "NOT ";
        }
        String authorWhere = "AND DOCUMENTS.Author " + authorNot + "IN (" + authors.stream().collect(Collectors.joining("', '")) + ") ";
        whereStatements = whereStatements + authorWhere;
        whereShortText = whereShortText + authorWhere;
        whereLongText = whereLongText + authorWhere;
        whereBoolean = whereBoolean + authorWhere;
        whereInteger = whereInteger + authorWhere;
    }
    if (sources != null && sources.size() > 0) {
        String sourceNot = "";
        if (!sourceInclude) {
            sourceNot = "NOT ";
        }
        String sourceWhere = "AND DOCUMENTS.Source " + sourceNot + "IN (" + sources.stream().collect(Collectors.joining("', '")) + ") ";
        whereStatements = whereStatements + sourceWhere;
        whereShortText = whereShortText + sourceWhere;
        whereLongText = whereLongText + sourceWhere;
        whereBoolean = whereBoolean + sourceWhere;
        whereInteger = whereInteger + sourceWhere;
    }
    if (sections != null && sections.size() > 0) {
        String sectionNot = "";
        if (!sectionInclude) {
            sectionNot = "NOT ";
        }
        String sectionWhere = "AND DOCUMENTS.Section " + sectionNot + "IN (" + sections.stream().collect(Collectors.joining("', '")) + ") ";
        whereStatements = whereStatements + sectionWhere;
        whereShortText = whereShortText + sectionWhere;
        whereLongText = whereLongText + sectionWhere;
        whereBoolean = whereBoolean + sectionWhere;
        whereInteger = whereInteger + sectionWhere;
    }
    if (types != null && types.size() > 0) {
        String typeNot = "";
        if (!typeInclude) {
            typeNot = "NOT ";
        }
        String typeWhere = "AND DOCUMENTS.Type " + typeNot + "IN (" + types.stream().collect(Collectors.joining("', '")) + ") ";
        whereStatements = whereStatements + typeWhere;
        whereShortText = whereShortText + typeWhere;
        whereLongText = whereLongText + typeWhere;
        whereBoolean = whereBoolean + typeWhere;
        whereInteger = whereInteger + typeWhere;
    }
    if (whereStatements.startsWith("AND")) {
        // ensure correct form if no statement ID filtering
        whereStatements = whereStatements.replaceFirst("AND", "WHERE");
    }
    String subString = "SUBSTRING(DOCUMENTS.Text, Start + 1, Stop - Start) AS Text ";
    if (Dna.sql.getConnectionProfile().getType().equals("postgresql")) {
        subString = "SUBSTRING(DOCUMENTS.Text, CAST(Start + 1 AS INT4), CAST(Stop - Start AS INT4)) AS Text ";
    }
    String q1 = "SELECT STATEMENTS.ID AS StatementId, " + "StatementTypeId, " + "STATEMENTTYPES.Label AS StatementTypeLabel, " + "STATEMENTTYPES.Red AS StatementTypeRed, " + "STATEMENTTYPES.Green AS StatementTypeGreen, " + "STATEMENTTYPES.Blue AS StatementTypeBlue, " + "Start, " + "Stop, " + "STATEMENTS.Coder AS CoderId, " + "CODERS.Name AS CoderName, " + "CODERS.Red AS CoderRed, " + "CODERS.Green AS CoderGreen, " + "CODERS.Blue AS CoderBlue, " + "DocumentId, " + "DOCUMENTS.Date AS Date, " + subString + "FROM STATEMENTS " + "INNER JOIN CODERS ON STATEMENTS.Coder = CODERS.ID " + "INNER JOIN STATEMENTTYPES ON STATEMENTS.StatementTypeId = STATEMENTTYPES.ID " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + whereStatements + "ORDER BY DOCUMENTS.DATE ASC;";
    String q2 = "SELECT ID FROM STATEMENTTYPES;";
    String q3 = "SELECT ID, Variable, DataType FROM VARIABLES;";
    String q4a = "SELECT DATASHORTTEXT.StatementId, VARIABLES.ID AS VariableId, ENTITIES.ID AS EntityId, ENTITIES.Value AS Value, ENTITIES.Red AS Red, ENTITIES.Green AS Green, ENTITIES.Blue AS Blue, ENTITIES.ChildOf AS ChildOf FROM DATASHORTTEXT " + "INNER JOIN VARIABLES ON VARIABLES.ID = DATASHORTTEXT.VariableId " + "INNER JOIN ENTITIES ON ENTITIES.VariableId = VARIABLES.ID AND ENTITIES.ID = DATASHORTTEXT.Entity " + "INNER JOIN STATEMENTS ON STATEMENTS.ID = DATASHORTTEXT.StatementId " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + "WHERE VARIABLES.StatementTypeId = ? " + whereShortText + "ORDER BY 1, 2 ASC;";
    String q4b = "SELECT DATALONGTEXT.StatementId, VARIABLES.ID AS VariableId, DATALONGTEXT.Value FROM DATALONGTEXT " + "INNER JOIN VARIABLES ON VARIABLES.ID = DATALONGTEXT.VariableId " + "INNER JOIN STATEMENTS ON STATEMENTS.ID = DATALONGTEXT.StatementId " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + "WHERE VARIABLES.StatementTypeId = ? " + whereLongText + "ORDER BY 1, 2 ASC;";
    String q4c = "SELECT DATABOOLEAN.StatementId, VARIABLES.ID AS VariableId, DATABOOLEAN.Value FROM DATABOOLEAN " + "INNER JOIN VARIABLES ON VARIABLES.ID = DATABOOLEAN.VariableId " + "INNER JOIN STATEMENTS ON STATEMENTS.ID = DATABOOLEAN.StatementId " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + "WHERE VARIABLES.StatementTypeId = ? " + whereBoolean + "ORDER BY 1, 2 ASC;";
    String q4d = "SELECT DATAINTEGER.StatementId, VARIABLES.ID AS VariableId, DATAINTEGER.Value FROM DATAINTEGER " + "INNER JOIN VARIABLES ON VARIABLES.ID = DATAINTEGER.VariableId " + "INNER JOIN STATEMENTS ON STATEMENTS.ID = DATAINTEGER.StatementId " + "INNER JOIN DOCUMENTS ON DOCUMENTS.ID = STATEMENTS.DocumentId " + "WHERE VARIABLES.StatementTypeId = ? " + whereInteger + "ORDER BY 1, 2 ASC;";
    String q5 = "SELECT AttributeVariable, AttributeValue FROM ATTRIBUTEVALUES " + "INNER JOIN ATTRIBUTEVARIABLES ON ATTRIBUTEVARIABLES.ID = AttributeVariableId " + "WHERE EntityId = ?;";
    ArrayList<Statement> listOfStatements = null;
    int statementTypeId, statementId, variableId, entityId;
    Color sColor, cColor;
    // variable ID to variable name
    HashMap<Integer, String> variableNameMap = new HashMap<Integer, String>();
    // variable ID to data type
    HashMap<Integer, String> variableDataTypeMap = new HashMap<Integer, String>();
    // statement ID to Statement
    HashMap<Integer, Statement> statementMap = new HashMap<Integer, Statement>();
    ResultSet r3, r4, r5;
    try (Connection conn = Dna.sql.getDataSource().getConnection();
        PreparedStatement s1 = conn.prepareStatement(q1);
        PreparedStatement s2 = conn.prepareStatement(q2);
        PreparedStatement s3 = conn.prepareStatement(q3);
        PreparedStatement s4a = conn.prepareStatement(q4a);
        PreparedStatement s4b = conn.prepareStatement(q4b);
        PreparedStatement s4c = conn.prepareStatement(q4c);
        PreparedStatement s4d = conn.prepareStatement(q4d);
        PreparedStatement s5 = conn.prepareStatement(q5)) {
        // assemble statements without values for now and save them in a hash map
        ResultSet r1 = s1.executeQuery();
        while (r1.next()) {
            statementId = r1.getInt("StatementId");
            statementTypeId = r1.getInt("StatementTypeId");
            sColor = new Color(r1.getInt("StatementTypeRed"), r1.getInt("StatementTypeGreen"), r1.getInt("StatementTypeBlue"));
            cColor = new Color(r1.getInt("CoderRed"), r1.getInt("CoderGreen"), r1.getInt("CoderBlue"));
            Statement statement = new Statement(statementId, r1.getInt("Start"), r1.getInt("Stop"), statementTypeId, r1.getString("StatementTypeLabel"), sColor, r1.getInt("CoderId"), r1.getString("CoderName"), cColor, new ArrayList<Value>(), r1.getInt("DocumentId"), r1.getString("Text"), LocalDateTime.ofEpochSecond(r1.getLong("Date"), 0, ZoneOffset.UTC));
            statementMap.put(statementId, statement);
        }
        // get variables
        r3 = s3.executeQuery();
        while (r3.next()) {
            variableNameMap.put(r3.getInt("ID"), r3.getString("Variable"));
            variableDataTypeMap.put(r3.getInt("ID"), r3.getString("DataType"));
        }
        // get statement types
        ResultSet r2 = s2.executeQuery();
        while (r2.next()) {
            statementTypeId = r2.getInt("ID");
            // get values and put them into the statements
            s4a.setInt(1, statementTypeId);
            r4 = s4a.executeQuery();
            while (r4.next()) {
                variableId = r4.getInt("VariableId");
                entityId = r4.getInt("EntityId");
                HashMap<String, String> map = new HashMap<String, String>();
                s5.setInt(1, entityId);
                r5 = s5.executeQuery();
                while (r5.next()) {
                    map.put(r5.getString("AttributeVariable"), r5.getString("AttributeValue"));
                }
                Entity e = new Entity(entityId, variableId, r4.getString("Value"), new Color(r4.getInt("Red"), r4.getInt("Green"), r4.getInt("Blue")), r4.getInt("ChildOf"), true, map);
                statementMap.get(r4.getInt("StatementId")).getValues().add(new Value(variableId, variableNameMap.get(variableId), variableDataTypeMap.get(variableId), e));
            }
            s4b.setInt(1, statementTypeId);
            r4 = s4b.executeQuery();
            while (r4.next()) {
                variableId = r4.getInt("VariableId");
                String value = r4.getString("Value");
                statementMap.get(r4.getInt("StatementId")).getValues().add(new Value(variableId, variableNameMap.get(variableId), variableDataTypeMap.get(variableId), value));
            }
            s4c.setInt(1, statementTypeId);
            r4 = s4c.executeQuery();
            while (r4.next()) {
                variableId = r4.getInt("VariableId");
                int value = r4.getInt("Value");
                statementMap.get(r4.getInt("StatementId")).getValues().add(new Value(variableId, variableNameMap.get(variableId), variableDataTypeMap.get(variableId), value));
            }
            s4d.setInt(1, statementTypeId);
            r4 = s4d.executeQuery();
            while (r4.next()) {
                variableId = r4.getInt("VariableId");
                int value = r4.getInt("Value");
                statementMap.get(r4.getInt("StatementId")).getValues().add(new Value(variableId, variableNameMap.get(variableId), variableDataTypeMap.get(variableId), value));
            }
        }
        // assemble and sort all statements
        Collection<Statement> s = statementMap.values();
        listOfStatements = new ArrayList<Statement>(s);
        Collections.sort(listOfStatements);
    } catch (SQLException e) {
        LogEvent l = new LogEvent(Logger.WARNING, "[SQL] Failed to retrieve statements.", "Attempted to retrieve a set of " + statementIds.length + " statements from the database, but something went wrong.", e);
        Dna.logger.log(l);
    }
    return listOfStatements;
}
Also used : Entity(model.Entity) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) LogEvent(logger.LogEvent) PreparedStatement(java.sql.PreparedStatement) Statement(model.Statement) Color(java.awt.Color) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) Value(model.Value)

Example 4 with Statement

use of model.Statement in project dna by leifeld.

the class MainWindow method newPopup.

/**
 * Show a statement popup window.
 *
 * @param x           X location on the screen.
 * @param y           Y location on the screen.
 * @param s           The statement to show.
 * @param documentId  The document ID for the statement.
 * @param location    The location of the popup window.
 * @param coder       The active coder.
 */
private void newPopup(double x, double y, Statement s, Point location) {
    // determine coders for the coder combo box in the popup window
    ArrayList<Coder> eligibleCoders = null;
    if (Dna.sql.getActiveCoder().isPermissionEditStatements() && Dna.sql.getActiveCoder().isPermissionEditOthersStatements() && (Dna.sql.getActiveCoder().isPermissionEditOthersStatements(s.getCoderId()) || Dna.sql.getActiveCoder().getId() == s.getCoderId())) {
        eligibleCoders = Dna.sql.getCoders();
        for (int i = eligibleCoders.size() - 1; i >= 0; i--) {
            if (Dna.sql.getActiveCoder().getId() != eligibleCoders.get(i).getId() && s.getCoderId() != eligibleCoders.get(i).getId() && !Dna.sql.getActiveCoder().isPermissionEditOthersStatements(eligibleCoders.get(i).getId())) {
                eligibleCoders.remove(i);
            }
        }
    }
    // create popup window
    this.popup = new Popup(x, y, s, location, Dna.sql.getActiveCoder(), eligibleCoders);
    // duplicate button action listener
    JButton duplicate = popup.getDuplicateButton();
    duplicate.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (Dna.sql.getActiveCoder().isPermissionAddStatements() == true) {
                // save popup changes
                if (popup.isEditable() == true && popup.hasWindowDecoration() == true) {
                    String message = "Save any changes in Statement " + s.getId() + " before creating copy?";
                    int dialog = JOptionPane.showConfirmDialog(popup, message, "Confirmation", JOptionPane.YES_NO_OPTION);
                    if (dialog == 0) {
                        popup.saveContents(false);
                    }
                } else if (popup.isEditable() && popup.hasWindowDecoration() == false) {
                    popup.saveContents(false);
                }
                // update statement table with changes to old statement that was saved
                statusBar.statementRefreshStart();
                Statement updatedOldStatement = popup.getStatementCopy();
                int modelRow = statementTableModel.getModelRowById(updatedOldStatement.getId());
                statementTableModel.getRow(modelRow).setCoderName(updatedOldStatement.getCoderName());
                statementTableModel.getRow(modelRow).setCoderColor(updatedOldStatement.getCoderColor());
                statementTableModel.fireTableRowsUpdated(modelRow, modelRow);
                // clone the statement
                int newStatementId = Dna.sql.cloneStatement(s.getId(), Dna.sql.getActiveCoder().getId());
                // repaint statements in text if old statement was changed or new statement successfully created
                if (newStatementId > 0 || (popup.isCoderChanged() && Dna.sql.getActiveCoder().isColorByCoder())) {
                    textPanel.paintStatements();
                }
                // put a cloned statement into the statement table and update view, then select statement
                if (newStatementId > 0) {
                    documentTableModel.increaseFrequency(updatedOldStatement.getDocumentId());
                    updatedOldStatement.setId(newStatementId);
                    updatedOldStatement.setCoderId(Dna.sql.getActiveCoder().getId());
                    updatedOldStatement.setCoderName(Dna.sql.getActiveCoder().getName());
                    updatedOldStatement.setCoderColor(Dna.sql.getActiveCoder().getColor());
                    statementTableModel.addRow(updatedOldStatement);
                    statementPanel.setSelectedStatementId(newStatementId);
                }
                popup.dispose();
                statusBar.statementRefreshEnd();
            }
        }
    });
    // remove button action listener
    JButton remove = popup.getRemoveButton();
    remove.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int question = JOptionPane.showConfirmDialog(MainWindow.this, "Are you sure you want to remove this statement?", "Remove?", JOptionPane.YES_NO_OPTION);
            if (question == 0) {
                statusBar.statementRefreshStart();
                boolean deleted = Dna.sql.deleteStatements(new int[] { s.getId() });
                if (deleted) {
                    getTextPanel().paintStatements();
                    documentTableModel.decreaseFrequency(s.getDocumentId());
                    int statementModelRow = statementTableModel.getModelRowById(s.getId());
                    getStatementPanel().getStatementTable().clearSelection();
                    statementTableModel.removeStatements(new int[] { statementModelRow });
                    // log deleted statements
                    LogEvent l = new LogEvent(Logger.MESSAGE, "[GUI] Action executed: removed statement(s).", "Deleted statement(s) in the database and GUI.");
                    Dna.logger.log(l);
                    popup.dispose();
                }
                statusBar.statementRefreshEnd();
            }
        }
    });
    // save and close window or focus listener
    if (popup.hasWindowDecoration() == true) {
        popup.addWindowListener(new // listener for the X button in the window decoration
        WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                if (popup.isEditable() == true) {
                    if (popup.saveContents(true) == true) {
                        // check first if there are any changes; ask to save only if necessary
                        String message = "Save changes in Statement " + s.getId() + "?";
                        int dialog = JOptionPane.showConfirmDialog(popup, message, "Confirmation", JOptionPane.YES_NO_OPTION);
                        if (dialog == 0) {
                            popupSave(popup);
                        }
                    }
                }
                popup.dispose();
                // clear statement table selection when popup window closed
                statementPanel.getStatementTable().clearSelection();
            }
        });
        popup.getCancelButton().addActionListener(new // cancel button action listener
        ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                popup.dispose();
                // clear statement table selection when popup window closed
                statementPanel.getStatementTable().clearSelection();
            }
        });
        popup.getSaveButton().addActionListener(new // save button action listener
        ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                popupSave(popup);
                popup.dispose();
                // clear statement table selection when popup window closed
                statementPanel.getStatementTable().clearSelection();
            }
        });
    // popup.setModal(true); // disabled for now: set modal after adding controls because otherwise controls can't be added anymore while modal
    } else {
        // no window decoration: focus lost listener
        popup.addWindowFocusListener(new WindowAdapter() {

            public void windowLostFocus(WindowEvent e) {
                popupSave(popup);
                popup.dispose();
                // clear statement table selection when popup window closed
                statementPanel.getStatementTable().clearSelection();
            }
        });
    }
    // needs to be called after setting modal; hence here instead of in the Popup class
    popup.setVisible(true);
}
Also used : Coder(model.Coder) LogEvent(logger.LogEvent) ActionEvent(java.awt.event.ActionEvent) PreparedStatement(java.sql.PreparedStatement) Statement(model.Statement) JButton(javax.swing.JButton) WindowAdapter(java.awt.event.WindowAdapter) Point(java.awt.Point) ActionListener(java.awt.event.ActionListener) WindowEvent(java.awt.event.WindowEvent)

Example 5 with Statement

use of model.Statement in project dna by leifeld.

the class Popup method getStatementCopy.

/**
 * Get an updated copy of the statement.
 *
 * @return The statement.
 */
Statement getStatementCopy() {
    Statement s = new Statement(this.statement);
    s.setCoderColor(this.coder.getColor());
    s.setCoderName(this.coder.getName());
    s.setCoderId(this.coder.getId());
    s.setValues(this.variables);
    return s;
}
Also used : Statement(model.Statement)

Aggregations

Statement (model.Statement)10 PreparedStatement (java.sql.PreparedStatement)7 LogEvent (logger.LogEvent)6 Color (java.awt.Color)5 Connection (java.sql.Connection)5 ResultSet (java.sql.ResultSet)5 SQLException (java.sql.SQLException)5 Point (java.awt.Point)3 ArrayList (java.util.ArrayList)3 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 JButton (javax.swing.JButton)2 Entity (model.Entity)2 Value (model.Value)2 DatePickerSettings (com.github.lgooddatepicker.components.DatePickerSettings)1 DateTimePicker (com.github.lgooddatepicker.components.DateTimePicker)1 TimePickerSettings (com.github.lgooddatepicker.components.TimePickerSettings)1 Dna (dna.Dna)1 BorderLayout (java.awt.BorderLayout)1 Component (java.awt.Component)1