Example usage for java.sql Types FLOAT

List of usage examples for java.sql Types FLOAT

Introduction

In this page you can find the example usage for java.sql Types FLOAT.

Prototype

int FLOAT

To view the source code for java.sql Types FLOAT.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type FLOAT.

Usage

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

/**
 * load mapping info/*from  ww  w  .  ja va2s  .c  om*/
 * 
 * @param type
 * @return
 */
private AnnoMappingInfo initMapInfo(final FeatureStructure fs) {
    final Type type = fs.getType();
    final String annoName = type.getShortName().toLowerCase();
    AnnoMappingInfo mapInfoTmp;
    final UimaType ut = uimaTypeMap.get(type.getName());
    if (this.mapAnnoMappingInfo.containsKey(type.getName())) {
        mapInfoTmp = this.mapAnnoMappingInfo.get(type.getName()).deepCopy();
    } else {
        mapInfoTmp = new AnnoMappingInfo();
    }
    final AnnoMappingInfo mapInfo = mapInfoTmp;
    if (ut != null)
        mapInfo.setUimaTypeId(ut.getUimaTypeID());
    // first see if the table name has been set in beans-uima.xml
    if (Strings.isNullOrEmpty(mapInfo.getTableName())) {
        // next see if the table name has been set in ref_uima_type
        if (ut != null && !Strings.isNullOrEmpty(ut.getTableName()))
            mapInfo.setTableName(ut.getTableName());
        else
            // default to anno_[short name]
            mapInfo.setTableName("anno_" + annoName);
    }
    final List<Feature> features = type.getFeatures();
    // get the non primitive fields
    for (Feature f : features) {
        if (f.getRange().isArray() && !f.getRange().getComponentType().isPrimitive()) {
            // add this field to the list of fields to store
            this.tl_mapFieldInfo.get().put(type.getName(), f.getShortName());
        }
    }
    this.sessionFactory.getCurrentSession().doWork(new Work() {
        @Override
        public void execute(Connection conn) throws SQLException {
            ResultSet rs = null;

            try {
                DatabaseMetaData dmd = conn.getMetaData();
                // get columns for corresponding table
                // mssql - add schema prefix
                // oracle - convert table name to upper case
                rs = dmd.getColumns(null, "mssql".equals(dbType) || "hsql".equals(dbType) ? dbSchema : null,
                        "orcl".equals(dbType) || "hsql".equals(dbType) ? mapInfo.getTableName().toUpperCase()
                                : mapInfo.getTableName(),
                        null);
                while (rs.next()) {
                    String colName = rs.getString("COLUMN_NAME");
                    int colSize = rs.getInt("COLUMN_SIZE");
                    int dataType = rs.getInt("DATA_TYPE");
                    if ("anno_base_id".equalsIgnoreCase(colName)) {
                        // skip anno_base_id
                        continue;
                    }
                    if ("uima_type_id".equalsIgnoreCase(colName)) {
                        // see if there is a uima_type_id column
                        // for FeatureStructures that are not annotations
                        // there can be a field for the uima_type_id
                        if (!(fs instanceof Annotation)
                                && Strings.isNullOrEmpty(mapInfo.getUimaTypeIdColumnName())) {
                            mapInfo.setUimaTypeIdColumnName(colName);
                        }
                    } else if ("coveredText".equalsIgnoreCase(colName)) {
                        // see if there is a coveredText column, store the
                        // covered
                        // text here
                        ColumnMappingInfo coveredTextColumn = new ColumnMappingInfo();
                        coveredTextColumn.setColumnName(colName);
                        mapInfo.setCoveredTextColumn(coveredTextColumn);
                        coveredTextColumn.setSize(colSize);
                    } else {
                        // possibility 1: the column is already mapped to
                        // the field
                        // if so, then just set the size
                        if (!updateSize(mapInfo, colName, colSize, dataType)) {
                            // possibility 2: the column is not mapped - see
                            // if
                            // it matches a field
                            // iterate through features, see which match the
                            // column
                            for (Feature f : features) {
                                String annoFieldName = f.getShortName();
                                if (f.getRange().isPrimitive() && annoFieldName.equalsIgnoreCase(colName)) {
                                    // primitive attribute
                                    ColumnMappingInfo fmap = new ColumnMappingInfo();
                                    fmap.setAnnoFieldName(annoFieldName);
                                    fmap.setColumnName(colName);
                                    fmap.setSize(colSize);
                                    fmap.setSqlType(dataType);
                                    mapInfo.getMapField().put(colName, fmap);
                                    break;
                                } else if (!f.getRange().isArray() && !f.getRange().isPrimitive()
                                        && annoFieldName.equalsIgnoreCase(colName)
                                        && (dataType == Types.INTEGER || dataType == Types.SMALLINT
                                                || dataType == Types.BIGINT || dataType == Types.NUMERIC
                                                || dataType == Types.FLOAT || dataType == Types.DOUBLE)) {
                                    // this feature is a reference to
                                    // another
                                    // annotation.
                                    // this column is numeric - a match
                                    ColumnMappingInfo fmap = new ColumnMappingInfo();
                                    fmap.setAnnoFieldName(annoFieldName);
                                    fmap.setColumnName(colName);
                                    fmap.setSize(colSize);
                                    fmap.setSqlType(dataType);
                                    mapInfo.getMapField().put(colName, fmap);
                                    break;
                                }
                            }
                        }
                    }
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                    }
                }
            }
        }
    });
    // don't map this annotation if no fields match columns
    if (mapInfo.getMapField().size() == 0 && mapInfo.getCoveredTextColumn() == null
            && Strings.isNullOrEmpty(mapInfo.getUimaTypeIdColumnName()))
        return null;
    // generate sql
    StringBuilder b = new StringBuilder("insert into ");
    b.append(this.getTablePrefix()).append(mapInfo.getTableName());
    b.append("(anno_base_id");
    // add coveredText column if available
    if (mapInfo.getCoveredTextColumn() != null) {
        b.append(", coveredText");
    }
    // add uima_type_id column if available
    if (mapInfo.getUimaTypeIdColumnName() != null) {
        b.append(", uima_type_id");
    }
    // add other fields
    for (Map.Entry<String, ColumnMappingInfo> fieldEntry : mapInfo.getMapField().entrySet()) {
        b.append(", ").append(dialect.openQuote()).append(fieldEntry.getValue().getColumnName())
                .append(dialect.closeQuote());
    }
    b.append(") values (?");
    // add coveredText bind param
    if (mapInfo.getCoveredTextColumn() != null) {
        b.append(", ?");
    }
    // add uimaTypeId bind param
    if (mapInfo.getUimaTypeIdColumnName() != null) {
        b.append(", ?");
    }
    // add bind params for other fields
    b.append(Strings.repeat(", ?", mapInfo.getMapField().size())).append(")");
    mapInfo.setSql(b.toString());
    if (log.isInfoEnabled())
        log.info("sql insert for type " + type.getName() + ": " + mapInfo.getSql());
    if (log.isDebugEnabled())
        log.debug("initMapInfo(" + annoName + "): " + mapInfo);
    return mapInfo;
}

From source file:org.jumpmind.symmetric.db.ase.AseTriggerTemplate.java

@Override
protected String buildKeyVariablesDeclare(Column[] columns, String prefix) {
    String text = "";
    for (int i = 0; i < columns.length; i++) {
        text += "declare @" + prefix + "pk" + i + " ";
        switch (columns[i].getMappedTypeCode()) {
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
            // ASE does not support bigint
            text += "NUMERIC(18,0)\n";
            break;
        case Types.NUMERIC:
        case Types.DECIMAL:
            // Use same default scale and precision used by Sybase ASA
            // for a decimal with unspecified scale and precision.
            text += "decimal(30,6)\n";
            break;
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
            text += "float\n";
            break;
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR:
            text += "varchar(1000)\n";
            break;
        case Types.DATE:
            text += "date\n";
            break;
        case Types.TIME:
            text += "time\n";
            break;
        case Types.TIMESTAMP:
            text += "datetime\n";
            break;
        case Types.BOOLEAN:
        case Types.BIT:
            text += "bit\n";
            break;
        case Types.CLOB:
            text += "varchar(32767)\n";
            break;
        case Types.BLOB:
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case -10: // SQL-Server ntext binary type
            text += "varbinary(32767)\n";
            break;
        case Types.OTHER:
            text += "varbinary(32767)\n";
            break;
        default:/*from  w w w  .  ja v a 2  s  .co m*/
            if (columns[i].getJdbcTypeName() != null
                    && columns[i].getJdbcTypeName().equalsIgnoreCase("interval")) {
                text += "interval";
                break;
            }
            throw new NotImplementedException(columns[i] + " is of type " + columns[i].getMappedType());
        }
    }

    return text;
}

From source file:io.bibleget.BibleGetDB.java

private void listColNamesTypes(DatabaseMetaData dbMeta, ResultSet rs) {
    //System.out.println("After Table Creation: Table "+rs.getString("TABLE_NAME")+" exists !!");
    ResultSet cols;/* w w w  .  j a v a2s .  co m*/
    try {
        cols = dbMeta.getColumns(null, null, rs.getString("TABLE_NAME"), null);
        while (cols.next()) {
            //System.out.println(cols.getString("COLUMN_NAME"));
            colNames.add(cols.getString("COLUMN_NAME"));
            int dType = cols.getInt("DATA_TYPE");
            switch (dType) {
            case Types.VARCHAR:
                colDataTypes.add(String.class);
                break;
            case Types.INTEGER:
                colDataTypes.add(Integer.class);
                break;
            case Types.FLOAT:
                colDataTypes.add(Float.class);
                break;
            case Types.DOUBLE:
            case Types.REAL:
                colDataTypes.add(Double.class);
                break;
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                colDataTypes.add(java.sql.Date.class);
                break;
            case Types.BOOLEAN:
                colDataTypes.add(Boolean.class);
                break;
            default:
                colDataTypes.add(String.class);
                break;
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.squid.kraken.v4.caching.redis.datastruct.RawMatrix.java

public static boolean isPrimitiveType(int colType) {

    switch (colType) {

    case Types.BIT:
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        return true;

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NUMERIC:
    case Types.DECIMAL:
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return false;

    default://from www . j  av a  2  s.c  o m
        return false;
    }
}

From source file:gsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;/* w ww  .  j  av  a  2  s.  c o m*/
    String query = getStatementInsert(tableName, fields).toString();
    try {
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.FLOAT:
                if (value == null)
                    ps.setNull(counter, Types.FLOAT);
                else
                    ps.setFloat(counter, ((Number) value).floatValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                logger.error("The type conversion is not supported for : " + dataField.getName() + "("
                        + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        //if (e.getType() == GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        //    if (logger.isDebugEnabled())
        //        logger.debug("An stream element dropped due to unexpected virtual sensor removal. (Stream element: " + streamElement.toString() + ")+ Query: " + query, e);
        //} else
        logger.warn("Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            logger.info("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        else
            logger.warn("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        throw e;
    } finally {
        close(ps);
    }
}

From source file:org.apache.ddlutils.TestAgainstLiveDatabaseBase.java

/**
 * Returns a copy of the given model adjusted for type changes because of the native type mappings
 * which when read back from the database will map to different types.
 * /*w  w  w  .ja  va 2  s  . c  om*/
 * @param sourceModel The source model
 * @return The adjusted model
 */
protected Database adjustModel(Database sourceModel) {
    Database model = new CloneHelper().clone(sourceModel);

    for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++) {
        Table table = model.getTable(tableIdx);

        for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++) {
            Column column = table.getColumn(columnIdx);
            int origType = column.getTypeCode();
            int targetType = getPlatformInfo().getTargetJdbcType(origType);

            // we adjust the column types if the native type would back-map to a
            // different jdbc type
            if (targetType != origType) {
                column.setTypeCode(targetType);
                // we should also adapt the default value
                if (column.getDefaultValue() != null) {
                    DefaultValueHelper helper = getPlatform().getSqlBuilder().getDefaultValueHelper();

                    column.setDefaultValue(helper.convert(column.getDefaultValue(), origType, targetType));
                }
            }
            // we also promote the default size if the column has no size
            // spec of its own
            if ((column.getSize() == null) && getPlatformInfo().hasSize(targetType)) {
                Integer defaultSize = getPlatformInfo().getDefaultSize(targetType);

                if (defaultSize != null) {
                    column.setSize(defaultSize.toString());
                }
            }
            // finally the platform might return a synthetic default value if the column
            // is a primary key column
            if (getPlatformInfo().isSyntheticDefaultValueForRequiredReturned()
                    && (column.getDefaultValue() == null) && column.isRequired() && !column.isAutoIncrement()) {
                switch (column.getTypeCode()) {
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.BIGINT:
                    column.setDefaultValue("0");
                    break;
                case Types.REAL:
                case Types.FLOAT:
                case Types.DOUBLE:
                    column.setDefaultValue("0.0");
                    break;
                case Types.BIT:
                    column.setDefaultValue("false");
                    break;
                default:
                    column.setDefaultValue("");
                    break;
                }
            }
            if (column.isPrimaryKey() && getPlatformInfo().isPrimaryKeyColumnAutomaticallyRequired()) {
                column.setRequired(true);
            }
            if (column.isAutoIncrement() && getPlatformInfo().isIdentityColumnAutomaticallyRequired()) {
                column.setRequired(true);
            }
        }
        // we also add the default names to foreign keys that are initially unnamed
        for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++) {
            ForeignKey fk = table.getForeignKey(fkIdx);

            if (fk.getName() == null) {
                fk.setName(getPlatform().getSqlBuilder().getForeignKeyName(table, fk));
            }
        }
    }
    return model;
}

From source file:rapture.repo.jdbc.JDBCStructuredStore.java

protected Map<String, Integer> getInputParamTypes(Map<String, Object> inParams) {
    Map<String, Integer> retMap = new HashMap<>();
    for (Map.Entry<String, Object> entry : inParams.entrySet()) {
        String clazz = entry.getValue().getClass().getSimpleName();
        switch (clazz) {
        case "String":
            retMap.put(entry.getKey(), Types.VARCHAR);
            break;
        case "Integer":
            retMap.put(entry.getKey(), Types.INTEGER);
            break;
        case "Float":
            retMap.put(entry.getKey(), Types.FLOAT);
            break;
        case "Double":
            retMap.put(entry.getKey(), Types.DOUBLE);
            break;
        case "Character":
            retMap.put(entry.getKey(), Types.CHAR);
            break;
        case "Boolean":
            retMap.put(entry.getKey(), Types.BOOLEAN);
            break;
        default:/*from   ww w. j  a va  2s.co m*/
            throw RaptureExceptionFactory.create("Unsupported class for param type");
        }
    }
    return retMap;
}

From source file:com.rapid.actions.Database.java

public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application,
        DataFactory df) throws Exception {

    // place holder for the object we're going to return
    JSONObject jsonData = null;/*from  w ww.ja  v a 2s  . c  o  m*/

    // retrieve the sql
    String sql = _query.getSQL();

    // only if there is some sql is it worth going further
    if (sql != null) {

        // get any json inputs
        JSONObject jsonInputData = jsonAction.optJSONObject("data");

        // initialise the parameters list
        ArrayList<Parameters> parametersList = new ArrayList<Parameters>();

        // populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
        if (_query.getInputs() == null) {

            // just add an empty parameters member if no inputs
            parametersList.add(new Parameters());

        } else {

            // if there is input data
            if (jsonInputData != null) {

                // get any input fields
                JSONArray jsonFields = jsonInputData.optJSONArray("fields");
                // get any input rows
                JSONArray jsonRows = jsonInputData.optJSONArray("rows");

                // if we have fields and rows
                if (jsonFields != null && jsonRows != null) {

                    // loop the input rows (only the top row if not multirow)
                    for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i++) {

                        // get this jsonRow
                        JSONArray jsonRow = jsonRows.getJSONArray(i);
                        // make the parameters for this row
                        Parameters parameters = new Parameters();

                        // loop the query inputs
                        for (Parameter input : _query.getInputs()) {
                            // get the input id
                            String id = input.getItemId();
                            // get the input field
                            String field = input.getField();
                            // add field to id if present
                            if (field != null && !"".equals(field))
                                id += "." + field;
                            // retain the value
                            String value = null;
                            // if it looks like a control, or a system value (bit of extra safety checking)
                            if ("P".equals(id.substring(0, 1)) && id.indexOf("_C") > 0
                                    || id.indexOf("System.") == 0) {
                                // loop the json inputs looking for the value
                                if (jsonInputData != null) {
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // get the id from the fields
                                        String jsonId = jsonFields.optString(j);
                                        // if the id we want matches this one 
                                        if (id.toLowerCase().equals(jsonId.toLowerCase())) {
                                            // get the value
                                            value = jsonRow.optString(j, null);
                                            // no need to keep looking
                                            break;
                                        }
                                    }
                                }
                            }
                            // if still null try the session
                            if (value == null)
                                value = (String) rapidRequest.getSessionAttribute(input.getItemId());
                            // add the parameter
                            parameters.add(value);
                        }

                        // add the parameters to the list
                        parametersList.add(parameters);

                    } // row loop

                } // input fields and rows check

            } // input data check

        } // query inputs check

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Database action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());

        }

        // if there isn't a cache or no data was retrieved
        if (jsonData == null) {

            try {

                // instantiate jsonData
                jsonData = new JSONObject();
                // fields collection
                JSONArray jsonFields = new JSONArray();
                // rows collection can start initialised
                JSONArray jsonRows = new JSONArray();

                // trim the sql
                sql = sql.trim();

                // check the verb
                if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with")) {

                    // set readonly to true (makes for faster querying)
                    df.setReadOnly(true);

                    // loop the parameterList getting a result set for each parameters (input row)
                    for (Parameters parameters : parametersList) {

                        // get the result set!
                        ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                        // get it's meta data for the field names
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // got fields indicator
                        boolean gotFields = false;

                        // loop the result set
                        while (rs.next()) {

                            // initialise the row
                            JSONArray jsonRow = new JSONArray();

                            // loop the columns
                            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                                // add the field name to the fields collection if not done yet
                                if (!gotFields)
                                    jsonFields.put(rsmd.getColumnLabel(i + 1));
                                // get the column type
                                int columnType = rsmd.getColumnType(i + 1);
                                // add the data to the row according to it's type   
                                switch (columnType) {
                                case (Types.NUMERIC):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                case (Types.INTEGER):
                                    jsonRow.put(rs.getInt(i + 1));
                                    break;
                                case (Types.BIGINT):
                                    jsonRow.put(rs.getLong(i + 1));
                                    break;
                                case (Types.FLOAT):
                                    jsonRow.put(rs.getFloat(i + 1));
                                    break;
                                case (Types.DOUBLE):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                default:
                                    jsonRow.put(rs.getString(i + 1));
                                }
                            }
                            // add the row to the rows collection
                            jsonRows.put(jsonRow);
                            // remember we now have our fields
                            gotFields = true;

                        }

                        // close the record set
                        rs.close();

                    }

                } else {

                    // assume rows affected is 0
                    int rows = 0;

                    // sql check
                    if (sql.length() > 0) {

                        // perform update for all incoming parameters (one parameters collection for each row)
                        for (Parameters parameters : parametersList) {
                            rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
                        }

                        // add a psuedo field 
                        jsonFields.put("rows");

                        // create a row array
                        JSONArray jsonRow = new JSONArray();
                        // add the rows updated
                        jsonRow.put(rows);
                        // add the row we just made
                        jsonRows.put(jsonRow);

                    }

                }

                // add the fields to the data object
                jsonData.put("fields", jsonFields);
                // add the rows to the data object
                jsonData.put("rows", jsonRows);

                // check for any child database actions
                if (_childDatabaseActions != null) {
                    // if there really are some
                    if (_childDatabaseActions.size() > 0) {
                        // get any child data
                        JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
                        // if there was some
                        if (jsonChildQueries != null) {
                            // loop
                            for (int i = 0; i < jsonChildQueries.length(); i++) {
                                // fetch the data
                                JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
                                // read the index (the position of the child this related to
                                int index = jsonChildAction.getInt("index");
                                // get the relevant child action
                                Database childDatabaseAction = _childDatabaseActions.get(index);
                                // get the resultant child data
                                JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest,
                                        jsonChildAction, application, df);

                                // a map for indexes of matching fields between our parent and child
                                Map<Integer, Integer> fieldsMap = new HashMap<Integer, Integer>();
                                // the child fields
                                JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
                                if (jsonChildFields != null) {
                                    // loop the parent fields
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // loop the child fields
                                        for (int k = 0; k < jsonChildFields.length(); k++) {
                                            // get parent field
                                            String field = jsonFields.getString(j);
                                            // get child field
                                            String childField = jsonChildFields.getString(k);
                                            // if both not null
                                            if (field != null && childField != null) {
                                                // check for match
                                                if (field.toLowerCase().equals(childField.toLowerCase()))
                                                    fieldsMap.put(j, k);
                                            }
                                        }
                                    }
                                }

                                // add a field for the results of this child action
                                jsonFields.put("childAction" + (i + 1));

                                // if matching fields
                                if (fieldsMap.size() > 0) {
                                    // an object with a null value for when there is no match
                                    Object nullObject = null;
                                    // get the child rows
                                    JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
                                    // if we had some
                                    if (jsonChildRows != null) {
                                        // loop the parent rows
                                        for (int j = 0; j < jsonRows.length(); j++) {
                                            // get the parent row
                                            JSONArray jsonRow = jsonRows.getJSONArray(j);
                                            // make a new rows collection for the child subset
                                            JSONArray jsonChildRowsSubset = new JSONArray();
                                            // loop the child rows
                                            for (int k = 0; k < jsonChildRows.length(); k++) {
                                                // get the child row
                                                JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
                                                // assume no matches
                                                int matches = 0;
                                                // loop the fields map
                                                for (Integer l : fieldsMap.keySet()) {
                                                    // parent value
                                                    Object parentValue = null;
                                                    // get the value if there are enough
                                                    if (jsonRow.length() > l)
                                                        parentValue = jsonRow.get(l);
                                                    // child value
                                                    Object childValue = null;
                                                    if (jsonChildRow.length() > l)
                                                        childValue = jsonChildRow.get(fieldsMap.get(l));
                                                    // non null check
                                                    if (parentValue != null && childValue != null) {
                                                        // a string we will concert the child value to
                                                        String parentString = null;
                                                        // check the parent value type
                                                        if (parentValue.getClass() == String.class) {
                                                            parentString = (String) parentValue;
                                                        } else if (parentValue.getClass() == Integer.class) {
                                                            parentString = Integer
                                                                    .toString((Integer) parentValue);
                                                        } else if (parentValue.getClass() == Long.class) {
                                                            parentString = Long.toString((Long) parentValue);
                                                        } else if (parentValue.getClass() == Double.class) {
                                                            parentString = Double
                                                                    .toString((Double) parentValue);
                                                        } else if (parentValue.getClass() == Boolean.class) {
                                                            parentString = Boolean
                                                                    .toString((Boolean) parentValue);
                                                        }
                                                        // a string we will convert the child value to
                                                        String childString = null;
                                                        // check the parent value type
                                                        if (childValue.getClass() == String.class) {
                                                            childString = (String) childValue;
                                                        } else if (childValue.getClass() == Integer.class) {
                                                            childString = Integer
                                                                    .toString((Integer) childValue);
                                                        } else if (childValue.getClass() == Long.class) {
                                                            childString = Long.toString((Long) childValue);
                                                        } else if (childValue.getClass() == Double.class) {
                                                            childString = Double.toString((Double) childValue);
                                                        } else if (childValue.getClass() == Boolean.class) {
                                                            childString = Boolean
                                                                    .toString((Boolean) childValue);
                                                        }
                                                        // non null check
                                                        if (parentString != null && childString != null) {
                                                            // do the match!
                                                            if (parentString.equals(childString))
                                                                matches++;
                                                        }
                                                    } // values non null                                          
                                                } // field map loop
                                                  // if we got some matches for all the fields add this row to the subset
                                                if (matches == fieldsMap.size())
                                                    jsonChildRowsSubset.put(jsonChildRow);
                                            } // child row loop
                                              // if our child subset has rows in it
                                            if (jsonChildRowsSubset.length() > 0) {
                                                // create a new childSubset object
                                                JSONObject jsonChildDataSubset = new JSONObject();
                                                // add the fields
                                                jsonChildDataSubset.put("fields", jsonChildFields);
                                                // add the subset of rows
                                                jsonChildDataSubset.put("rows", jsonChildRowsSubset);
                                                // add the child database action data subset
                                                jsonRow.put(jsonChildDataSubset);
                                            } else {
                                                // add an empty cell
                                                jsonRow.put(nullObject);
                                            }
                                        } // parent row loop                                 
                                    } // jsonChildRows null check
                                } else {
                                    // loop the parent rows
                                    for (int j = 0; j < jsonRows.length(); j++) {
                                        // get the row
                                        JSONArray jsonRow = jsonRows.getJSONArray(j);
                                        // add the child database action data
                                        jsonRow.put(jsonChildData);
                                    }
                                } // matching fields check

                            } // jsonChildQueries loop
                        } // jsonChildQueries null check                      
                    } // _childDatabaseActions size > 0                                                      
                } // _childDatabaseActions not null

                // cache if in use
                if (actionCache != null)
                    actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);

            } catch (Exception ex) {

                // log the error
                _logger.error(ex);

                // close the data factory and silently fail
                try {
                    df.close();
                } catch (Exception ex2) {
                }

                // only throw if no action cache
                if (actionCache == null) {
                    throw ex;
                } else {
                    _logger.debug("Error not shown to user due to cache : " + ex.getMessage());
                }

            } // jsonData not null

        } // jsonData == null

    } // got sql

    return jsonData;

}

From source file:org.jumpmind.symmetric.db.AbstractTriggerTemplate.java

protected ColumnString fillOutColumnTemplate(String origTableAlias, String tableAlias, String columnPrefix,
        Column column, DataEventType dml, boolean isOld, Channel channel, Trigger trigger) {
    boolean isLob = symmetricDialect.getPlatform().isLob(column.getMappedTypeCode());
    String templateToUse = null;/*from  www.j a  va  2s. c  o  m*/
    if (column.getJdbcTypeName() != null && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
            && StringUtils.isNotBlank(geometryColumnTemplate)) {
        templateToUse = geometryColumnTemplate;
    } else if (column.getJdbcTypeName() != null
            && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
            && StringUtils.isNotBlank(geographyColumnTemplate)) {
        templateToUse = geographyColumnTemplate;
    } else {
        switch (column.getMappedTypeCode()) {
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
        case Types.NUMERIC:
        case Types.DECIMAL:
            templateToUse = numberColumnTemplate;
            break;
        case Types.CHAR:
        case Types.NCHAR:
        case Types.VARCHAR:
        case ColumnTypes.NVARCHAR:
            templateToUse = stringColumnTemplate;
            break;
        case ColumnTypes.SQLXML:
            templateToUse = xmlColumnTemplate;
            break;
        case Types.ARRAY:
            templateToUse = arrayColumnTemplate;
            break;
        case Types.LONGVARCHAR:
        case ColumnTypes.LONGNVARCHAR:
            if (!isLob) {
                templateToUse = stringColumnTemplate;
                break;
            }
        case Types.CLOB:
            if (isOld && symmetricDialect.needsToSelectLobData()) {
                templateToUse = emptyColumnTemplate;
            } else {
                templateToUse = clobColumnTemplate;
            }
            break;
        case Types.BINARY:
        case Types.VARBINARY:
            if (isNotBlank(binaryColumnTemplate)) {
                templateToUse = binaryColumnTemplate;
                break;
            }
        case Types.BLOB:
            if (requiresWrappedBlobTemplateForBlobType()) {
                templateToUse = wrappedBlobColumnTemplate;
                break;
            }
        case Types.LONGVARBINARY:
        case -10: // SQL-Server ntext binary type
            if (column.getJdbcTypeName() != null
                    && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.IMAGE))
                    && StringUtils.isNotBlank(imageColumnTemplate)) {
                if (isOld) {
                    templateToUse = emptyColumnTemplate;
                } else {
                    templateToUse = imageColumnTemplate;
                }
            } else if (isOld && symmetricDialect.needsToSelectLobData()) {
                templateToUse = emptyColumnTemplate;
            } else {
                templateToUse = blobColumnTemplate;
            }
            break;
        case Types.DATE:
            if (noDateColumnTemplate()) {
                templateToUse = datetimeColumnTemplate;
                break;
            }
            templateToUse = dateColumnTemplate;
            break;
        case Types.TIME:
            if (noTimeColumnTemplate()) {
                templateToUse = datetimeColumnTemplate;
                break;
            }
            templateToUse = timeColumnTemplate;
            break;
        case Types.TIMESTAMP:
            templateToUse = datetimeColumnTemplate;
            break;
        case Types.BOOLEAN:
        case Types.BIT:
            templateToUse = booleanColumnTemplate;
            break;
        default:
            if (column.getJdbcTypeName() != null) {
                if (column.getJdbcTypeName().toUpperCase().equals(TypeMap.INTERVAL)) {
                    templateToUse = numberColumnTemplate;
                    break;
                } else if (column.getMappedType().equals(TypeMap.TIMESTAMPTZ)
                        && StringUtils.isNotBlank(this.dateTimeWithTimeZoneColumnTemplate)) {
                    templateToUse = this.dateTimeWithTimeZoneColumnTemplate;
                    break;
                } else if (column.getMappedType().equals(TypeMap.TIMESTAMPLTZ)
                        && StringUtils.isNotBlank(this.dateTimeWithLocalTimeZoneColumnTemplate)) {
                    templateToUse = this.dateTimeWithLocalTimeZoneColumnTemplate;
                    break;
                }

            }

            if (StringUtils.isBlank(templateToUse) && StringUtils.isNotBlank(this.otherColumnTemplate)) {
                templateToUse = this.otherColumnTemplate;
                break;
            }

            throw new NotImplementedException(column.getName() + " is of type " + column.getMappedType()
                    + " with JDBC type of " + column.getJdbcTypeName());
        }
    }

    if (dml == DataEventType.DELETE && isLob && requiresEmptyLobTemplateForDeletes()) {
        templateToUse = emptyColumnTemplate;
    } else if (isLob && trigger.isUseStreamLobs()) {
        templateToUse = emptyColumnTemplate;
    }

    if (templateToUse != null) {
        templateToUse = templateToUse.trim();
    } else {
        throw new NotImplementedException();
    }

    String formattedColumnText = FormatUtils.replace("columnName",
            String.format("%s%s", columnPrefix, column.getName()), templateToUse);

    formattedColumnText = FormatUtils.replace("columnSize", column.getSize(), formattedColumnText);

    formattedColumnText = FormatUtils.replace("masterCollation", symmetricDialect.getMasterCollation(),
            formattedColumnText);

    if (isLob) {
        formattedColumnText = symmetricDialect.massageForLob(formattedColumnText, channel);
    }

    formattedColumnText = FormatUtils.replace("origTableAlias", origTableAlias, formattedColumnText);
    formattedColumnText = FormatUtils.replace("tableAlias", tableAlias, formattedColumnText);
    formattedColumnText = FormatUtils.replace("prefixName", symmetricDialect.getTablePrefix(),
            formattedColumnText);

    return new ColumnString(formattedColumnText, isLob);

}

From source file:org.jumpmind.vaadin.ui.sqlexplorer.TabularResultLayout.java

private void setEditor(Grid.Column gridColumn, Column tableColumn, List<TextField> primaryKeyEditors) {
    TextField editor = new TextField();
    int typeCode = tableColumn.getMappedTypeCode();

    switch (typeCode) {
    case Types.DATE:
        editor.setConverter(new ObjectConverter(Date.class, typeCode));
        break;//from w ww.j  a  v  a 2 s .c om
    case Types.TIME:
        editor.setConverter(new ObjectConverter(Time.class, typeCode));
        break;
    case Types.TIMESTAMP:
        editor.setConverter(new ObjectConverter(Timestamp.class, typeCode));
        break;
    case Types.BIT:
        editor.setConverter(new StringToBooleanConverter());
        break;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.BIGINT:
    case Types.INTEGER:
        editor.setConverter(new StringToLongConverter() {
            private static final long serialVersionUID = 1L;

            public NumberFormat getFormat(Locale locale) {
                NumberFormat format = super.getFormat(locale);
                format.setGroupingUsed(false);
                return format;
            }
        });
        break;
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.NUMERIC:
    case Types.DECIMAL:
        editor.setConverter(new StringToBigDecimalConverter() {
            private static final long serialVersionUID = 1L;

            public NumberFormat getFormat(Locale locale) {
                NumberFormat format = super.getFormat(locale);
                format.setGroupingUsed(false);
                return format;
            }
        });
        break;
    default:
        break;
    }

    editor.addValidator(new TableChangeValidator(editor, tableColumn));

    editor.setNullRepresentation("");
    if (!tableColumn.isRequired()) {
        editor.setNullSettingAllowed(true);
    }

    if (tableColumn.isPrimaryKey()) {
        primaryKeyEditors.add(editor);
    }

    gridColumn.setEditorField(editor);
}