Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
AnalyzerBeans Copyright (C) 2014 Neopost - Customer Information Management This copyrighted material is made available to anyone wishing to use, modify, copy, or redistribute it subject to the terms and conditions of the GNU Lesser General Public License, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this distribution; if not, write to: Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA
 
 package org.eobjects.analyzer.storage;
 
 import java.util.List;
 import java.util.Map;
 
 
 
     private final static Logger logger = LoggerFactory.getLogger(SqlDatabaseRowAnnotationFactory.class);
     private final Map<InputColumn<?>, String_inputColumnNames = new LinkedHashMap<InputColumn<?>, String>();
     private final Map<RowAnnotationString_annotationColumnNames = new HashMap<RowAnnotationString>();
     private final Connection _connection;
     private final String _tableName;
     private final AtomicInteger _nextColumnIndex = new AtomicInteger(1);
 
     public SqlDatabaseRowAnnotationFactory(Connection connectionString tableName) {
          = connection;
          = tableName;
         String intType = SqlDatabaseUtils.getSqlType(Integer.class);
         performUpdate(. + tableName + " (id " + intType
                 + " PRIMARY KEY, distinct_count " + intType + ")");
     }
 
     @Override
     protected void finalize() throws Throwable {
         super.finalize();
         performUpdate("DROP TABLE " + );
     }
 
     private void performUpdate(String sql) {
         SqlDatabaseUtils.performUpdate(sql);
     }
 
     @Override
     public RowAnnotation createAnnotation() {
         return new RowAnnotationImpl();
     }
 
     private boolean containsRow(InputRow row) {
         ResultSet rs = null;
         PreparedStatement st = null;
         try {
             st = .prepareStatement("SELECT COUNT(*) FROM " +  + " WHERE id = ?");
             boolean contains;
             st.setInt(1, row.getId());
             rs = st.executeQuery();
             if (rs.next()) {
                 int count = rs.getInt(1);
                 if (count == 0) {
                     contains = false;
                 } else if (count == 1) {
                     contains = true;
                 } else {
                     throw new IllegalStateException(count + " rows with id=" + row.getId() + " exists in database!");
                 }
             } else {
                 contains = false;
             }
             return contains;
         } catch (SQLException e) {
             throw new IllegalStateException(e);
         } finally {
             SqlDatabaseUtils.safeClose(rsst);
         }
     }
 
    @Override
    public void annotate(InputRow[] rowsRowAnnotation annotation) {
        for (InputRow row : rows) {
            annotate(row, 1, annotation);
        }
    }
    @Override
    public synchronized void annotate(InputRow rowint distinctCountRowAnnotation annotation) {
        RowAnnotationImpl a = (RowAnnotationImplannotation;
        List<InputColumn<?>> inputColumns = row.getInputColumns();
        List<StringcolumnNames = new ArrayList<String>(inputColumns.size());
        List<Objectvalues = new ArrayList<Object>(inputColumns.size());
        for (InputColumn<?> inputColumn : inputColumns) {
            String columnName = getColumnName(inputColumntrue);
            columnNames.add(columnName);
            Object value = row.getValue(inputColumn);
            values.add(value);
        }
        String annotationColumnName = getColumnName(annotationtrue);
        if (containsRow(row)) {
            PreparedStatement st = null;
            ResultSet rs = null;
            boolean annotated;
            try {
                st = .prepareStatement("SELECT " + annotationColumnName + " FROM " + 
                        + " WHERE id=?");
                st.setInt(1, row.getId());
                rs = st.executeQuery();
                if (rs.next()) {
                    annotated = rs.getBoolean(1);
                } else {
                    .error("No rows returned on annotation status for id={}"row.getId());
                    annotated = false;
                }
            } catch (SQLException e) {
                throw new IllegalStateException(e);
            } finally {
                SqlDatabaseUtils.safeClose(rsst);
            }
            if (!annotated) {
                try {
                    st = .prepareStatement("UPDATE " +  + " SET " + annotationColumnName
                            + "=TRUE WHERE id=?");
                    st.setInt(1, row.getId());
                    st.executeUpdate();
                    a.incrementRowCount(distinctCount);
                } catch (SQLException e) {
                    throw new IllegalStateException(e);
                } finally {
                    SqlDatabaseUtils.safeClose(nullst);
                }
            }
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("INSERT INTO ");
            sb.append();
            sb.append(" (id,distinct_count");
            sb.append(',');
            sb.append(annotationColumnName);
            for (String columnName : columnNames) {
                sb.append(',');
                sb.append(columnName);
            }
            sb.append(") VALUES (?,?,?");
            for (int i = 0; i < values.size(); i++) {
                sb.append(",?");
            }
            sb.append(")");
            PreparedStatement st = null;
            try {
                st = .prepareStatement(sb.toString());
                st.setInt(1, row.getId());
                st.setInt(2, distinctCount);
                st.setBoolean(3, true);
                for (int i = 0; i < values.size(); i++) {
                    st.setObject(i + 4, values.get(i));
                }
                st.executeUpdate();
                a.incrementRowCount(distinctCount);
            } catch (SQLException e) {
                throw new IllegalStateException(e);
            } finally {
                SqlDatabaseUtils.safeClose(nullst);
            }
        }
    }
    private String getColumnName(RowAnnotation annotationboolean createIfNonExisting) {
        String columnName = .get(annotation);
        if (columnName == null) {
            if (createIfNonExisting) {
                int index = .getAndIncrement();
                columnName = "col" + index;
                performUpdate("ALTER TABLE " +  + " ADD COLUMN " + columnName + " "
                        + SqlDatabaseUtils.getSqlType(Boolean.class) + " DEFAULT FALSE");
                .put(annotationcolumnName);
            }
        }
        return columnName;
    }
    private String getColumnName(InputColumn<?> inputColumnboolean createIfNonExisting) {
        String columnName = .get(inputColumn);
        if (columnName == null) {
            if (createIfNonExisting) {
                int index = .getAndIncrement();
                columnName = "col" + index;
                Class<?> javaType = inputColumn.getDataType();
                performUpdate("ALTER TABLE " +  + " ADD COLUMN " + columnName + " "
                        + SqlDatabaseUtils.getSqlType(javaType));
                .put(inputColumncolumnName);
            }
        }
        return columnName;
    }
    @Override
    public synchronized void reset(RowAnnotation annotation) {
        String columnName = getColumnName(annotationfalse);
        if (columnName != null) {
            performUpdate("UPDATE " +  + " SET " + columnName + " = FALSE");
        }
    }
    @Override
    public InputRow[] getRows(RowAnnotation annotation) {
        String annotationColumnName = getColumnName(annotationfalse);
        if (annotationColumnName == null) {
            return new InputRow[0];
        }
        ResultSet rs = null;
        Statement st = null;
        try {
            st = .createStatement();
            StringBuilder sb = new StringBuilder();
            sb.append("SELECT id");
            ArrayList<InputColumn<?>> inputColumns = new ArrayList<InputColumn<?>>(.keySet());
            for (InputColumn<?> inputColumn : inputColumns) {
                sb.append(',');
                String columnName = .get(inputColumn);
                sb.append(columnName);
            }
            sb.append(" FROM ");
            sb.append();
            sb.append(" WHERE ");
            sb.append(annotationColumnName);
            sb.append(" = TRUE");
            rs = st.executeQuery(sb.toString());
            List<InputRowrows = new ArrayList<InputRow>();
            while (rs.next()) {
                int id = rs.getInt(1);
                MockInputRow row = new MockInputRow(id);
                int colIndex = 2;
                for (InputColumn<?> inputColumn : inputColumns) {
                    Object value = rs.getObject(colIndex);
                    row.put(inputColumnvalue);
                    colIndex++;
                }
                rows.add(row);
            }
            return rows.toArray(new InputRow[rows.size()]);
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        } finally {
            SqlDatabaseUtils.safeClose(rsst);
        }
    }
    @Override
    public Map<ObjectIntegergetValueCounts(RowAnnotation annotationInputColumn<?> inputColumn) {
        HashMap<ObjectIntegermap = new HashMap<ObjectInteger>();
        String inputColumnName = getColumnName(inputColumnfalse);
        if (inputColumnName == null) {
            return map;
        }
        String annotationColumnName = getColumnName(annotationfalse);
        if (annotationColumnName == null) {
            return map;
        }
        ResultSet rs = null;
        PreparedStatement st = null;
        try {
            st = .prepareStatement("SELECT " + inputColumnName + ", SUM(distinct_count) FROM " + 
                    + " WHERE " + annotationColumnName + " = TRUE GROUP BY " + inputColumnName);
            rs = st.executeQuery();
            while (rs.next()) {
                Object value = rs.getObject(1);
                int count = rs.getInt(2);
                map.put(valuecount);
            }
            return map;
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        } finally {
            SqlDatabaseUtils.safeClose(rsst);
        }
    }
    @Override
    public void transferAnnotations(RowAnnotation fromRowAnnotation to) {
        final int increment = from.getRowCount();
        ((RowAnnotationImplto).incrementRowCount(increment);
        
        // TODO: Copy records to new annotation also?
    }
New to GrepCode? Check out our FAQ X