Example usage for java.sql Types NUMERIC

List of usage examples for java.sql Types NUMERIC

Introduction

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

Prototype

int NUMERIC

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

Click Source Link

Document

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

Usage

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

@Override
public List<Long> getPageIds(int objectType, long objectId, PageState state) {
    return getExtendedJdbcTemplate().queryForList(
            getBoundSql("ARCHITECTURE_COMMUNITY.SELECT_PAGE_IDS_BY_OBJECT_TYPE_AND_OBJECT_ID_AND_STATE")
                    .getSql(),/* w  ww.j a  v  a 2  s . co  m*/
            Long.class, new SqlParameterValue(Types.NUMERIC, objectType),
            new SqlParameterValue(Types.NUMERIC, objectId),
            new SqlParameterValue(Types.VARCHAR, state.name().toLowerCase()));
}

From source file:org.dspace.storage.rdbms.DatabaseManager.java

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results//  w  ww. j a v  a 2  s .co m
 *            A ResultSet to process
 * @param table
 *            The name of the table
 * @param pColumnNames
 *            The name of the columns in this resultset
 * @return A TableRow object with the data from the ResultSet
 * @exception SQLException
 *                If a database error occurs
 */
static TableRow process(ResultSet results, String table, List<String> pColumnNames) throws SQLException {
    ResultSetMetaData meta = results.getMetaData();
    int columns = meta.getColumnCount() + 1;

    // If we haven't been passed the column names try to generate them from the metadata / table
    List<String> columnNames = pColumnNames != null ? pColumnNames
            : ((table == null) ? getColumnNames(meta) : getColumnNames(table));

    TableRow row = new TableRow(canonicalize(table), columnNames);

    // Process the columns in order
    // (This ensures maximum backwards compatibility with
    // old JDBC drivers)
    for (int i = 1; i < columns; i++) {
        String name = meta.getColumnName(i);
        int jdbctype = meta.getColumnType(i);

        switch (jdbctype) {
        case Types.BIT:
            row.setColumn(name, results.getBoolean(i));
            break;

        case Types.INTEGER:
        case Types.NUMERIC:
            if (isOracle) {
                long longValue = results.getLong(i);
                if (longValue <= (long) Integer.MAX_VALUE) {
                    row.setColumn(name, (int) longValue);
                } else {
                    row.setColumn(name, longValue);
                }
            } else {
                row.setColumn(name, results.getInt(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            row.setColumn(name, results.getLong(i));
            break;

        case Types.DOUBLE:
            row.setColumn(name, results.getDouble(i));
            break;

        case Types.CLOB:
            if (isOracle) {
                row.setColumn(name, results.getString(i));
            } else {
                throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
            }
            break;

        case Types.VARCHAR:
            try {
                byte[] bytes = results.getBytes(i);

                if (bytes != null) {
                    String mystring = new String(results.getBytes(i), "UTF-8");
                    row.setColumn(name, mystring);
                } else {
                    row.setColumn(name, results.getString(i));
                }
            } catch (UnsupportedEncodingException e) {
                log.error("Unable to parse text from database", e);
            }
            break;

        case Types.DATE:
            row.setColumn(name, results.getDate(i));
            break;

        case Types.TIME:
            row.setColumn(name, results.getTime(i));
            break;

        case Types.TIMESTAMP:
            row.setColumn(name, results.getTimestamp(i));
            break;

        default:
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype);
        }

        // Determines if the last column was null, and sets the tablerow accordingly
        if (results.wasNull()) {
            row.setColumnNull(name);
        }
    }

    // Now that we've prepped the TableRow, reset the flags so that we can detect which columns have changed
    row.resetChanged();
    return row;
}

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

@Override
public List<Long> getPageIds(int objectType, long objectId, PageState state, int startIndex, int maxResults) {
    return getExtendedJdbcTemplate().queryScrollable(
            getBoundSql("ARCHITECTURE_COMMUNITY.SELECT_PAGE_IDS_BY_OBJECT_TYPE_AND_OBJECT_ID_AND_STATE")
                    .getSql(),//from   w  ww  .  j a v a2  s.  com
            startIndex, maxResults, new Object[] { objectType, objectId, state.name().toLowerCase() },
            new int[] { Types.NUMERIC, Types.NUMERIC, Types.VARCHAR }, Long.class);
}

From source file:org.springframework.jdbc.object.SqlQueryTests.java

private void doTestNamedParameterCustomerQuery(final boolean namedDeclarations) throws SQLException {
    mockResultSet.next();//from  w w w . j  a va2  s  .c  o m
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(1);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("rod");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setString(2, "UK");
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    class CustomerQuery extends MappingSqlQuery {

        public CustomerQuery(DataSource ds) {
            super(ds, SELECT_ID_FORENAME_NAMED_PARAMETERS);
            setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
            if (namedDeclarations) {
                declareParameter(new SqlParameter("country", Types.VARCHAR));
                declareParameter(new SqlParameter("id", Types.NUMERIC));
            } else {
                declareParameter(new SqlParameter(Types.NUMERIC));
                declareParameter(new SqlParameter(Types.VARCHAR));
            }
            compile();
        }

        protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
            Customer cust = new Customer();
            cust.setId(rs.getInt(COLUMN_NAMES[0]));
            cust.setForename(rs.getString(COLUMN_NAMES[1]));
            return cust;
        }

        public Customer findCustomer(int id, String country) {
            Map params = new HashMap();
            params.put("id", new Integer(id));
            params.put("country", country);
            return (Customer) executeByNamedParam(params).get(0);
        }
    }

    CustomerQuery query = new CustomerQuery(mockDataSource);
    Customer cust = query.findCustomer(1, "UK");
    assertTrue("Customer id was assigned correctly", cust.getId() == 1);
    assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
}

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

@Override
public int getPageCount(int objectType, long objectId, PageState state) {
    return getExtendedJdbcTemplate().queryForObject(
            getBoundSql("ARCHITECTURE_COMMUNITY.COUNT_PAGE_BY_OBJECT_TYPE_AND_OBJECT_ID_AND_STATE").getSql(),
            Integer.class, new SqlParameterValue(Types.NUMERIC, objectType),
            new SqlParameterValue(Types.NUMERIC, objectId),
            new SqlParameterValue(Types.VARCHAR, state.name().toLowerCase()));
}

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;/* w  ww .j  a v  a 2s .  c  om*/

    // 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:com.flexive.core.storage.genericSQL.GenericBinarySQLStorage.java

/**
 * Transfer a binary from the transit to the 'real' binary table
 *
 * @param _con     open and valid connection
 * @param binary  the binary descriptor//from   www .ja  va2 s.  c o  m
 * @param id      desired id
 * @param version desired version
 * @param quality desired quality
 * @return descriptor of final binary
 * @throws FxDbException on errors looking up the sequencer
 */
private BinaryDescriptor binaryTransit(Connection _con, BinaryDescriptor binary, long id, int version,
        int quality) throws FxDbException {
    PreparedStatement ps = null;
    BinaryDescriptor created;
    FileInputStream fis = null;
    boolean dbTransit;
    boolean dbStorage;
    final long dbThreshold;
    final long dbPreviewThreshold;
    final int divisionId = FxContext.get().getDivisionId();
    try {
        final DivisionConfigurationEngine divisionConfig = EJBLookup.getDivisionConfigurationEngine();
        dbTransit = divisionConfig.get(SystemParameters.BINARY_TRANSIT_DB);
        if (id >= 0) {
            dbThreshold = divisionConfig.get(SystemParameters.BINARY_DB_THRESHOLD);
            dbPreviewThreshold = divisionConfig.get(SystemParameters.BINARY_DB_PREVIEW_THRESHOLD);
        } else {
            //force storage of system binaries in the database
            dbThreshold = -1;
            dbPreviewThreshold = -1;
        }
        dbStorage = dbThreshold < 0 || binary.getSize() < dbThreshold;
    } catch (FxApplicationException e) {
        throw e.asRuntimeException();
    }
    Connection con = null;
    try {
        con = Database.getNonTXDataSource(divisionId).getConnection();
        con.setAutoCommit(false);
        double resolution = 0.0;
        int width = 0;
        int height = 0;
        boolean isImage = binary.getMimeType().startsWith("image/");
        if (isImage) {
            try {
                width = Integer
                        .parseInt(defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "width"), "0"));
                height = Integer.parseInt(
                        defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "height"), "0"));
                resolution = Double.parseDouble(
                        defaultString(FxXMLUtils.getElementData(binary.getMetadata(), "xResolution"), "0"));
            } catch (NumberFormatException e) {
                //ignore
                LOG.warn(e, e);
            }
        }
        created = new BinaryDescriptor(CacheAdmin.getStreamServers(), id, version, quality,
                System.currentTimeMillis(), binary.getName(), binary.getSize(), binary.getMetadata(),
                binary.getMimeType(), isImage, resolution, width, height, binary.getMd5sum());
        //we can copy the blob directly into the binary table if the database is used for transit and the final binary is
        //stored in the filesystem
        final boolean copyBlob = dbTransit && dbStorage;
        boolean storePrev1FS = false, storePrev2FS = false, storePrev3FS = false, storePrev4FS = false;
        long prev1Length = -1, prev2Length = -1, prev3Length = -1, prev4Length = -1;
        if (dbPreviewThreshold >= 0) {
            //we have to check if preview should be stored on the filesystem
            ps = con.prepareStatement(BINARY_TRANSIT_PREVIEW_SIZES);
            ps.setString(1, binary.getHandle());
            ResultSet rs = ps.executeQuery();
            if (!rs.next())
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
            rs.getLong(1); //check if previewref is null
            if (rs.wasNull()) {
                //if previews are not referenced, check thresholds
                storePrev1FS = (prev1Length = rs.getLong(2)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev2FS = (prev2Length = rs.getLong(3)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev3FS = (prev3Length = rs.getLong(4)) >= dbPreviewThreshold && !rs.wasNull();
                storePrev4FS = (prev4Length = rs.getLong(5)) >= dbPreviewThreshold && !rs.wasNull();
            }
        }
        if (ps != null)
            ps.close();
        String previewSelect = (storePrev1FS ? ",NULL" : ",PREV1") + (storePrev2FS ? ",NULL" : ",PREV2")
                + (storePrev3FS ? ",NULL" : ",PREV3") + (storePrev4FS ? ",NULL" : ",PREV4");
        //check if the binary is to be replaced
        ps = con.prepareStatement(
                "SELECT COUNT(*) FROM " + TBL_CONTENT_BINARY + " WHERE ID=? AND VER=? AND QUALITY=?");
        ps.setLong(1, created.getId());
        ps.setInt(2, created.getVersion()); //version
        ps.setInt(3, created.getQuality()); //quality
        ResultSet rsExist = ps.executeQuery();
        final boolean replaceBinary = rsExist != null && rsExist.next() && rsExist.getLong(1) > 0;
        ps.close();
        int paramIndex = 1;
        if (replaceBinary) {
            ps = con.prepareStatement(BINARY_TRANSIT_REPLACE
                    + (copyBlob ? BINARY_TRANSIT_REPLACE_FBLOB_COPY : BINARY_TRANSIT_REPLACE_FBLOB_PARAM)
                    + BINARY_TRANSIT_REPLACE_PARAMS);
            FxBinaryUtils.removeBinary(divisionId, created.getId());
        } else {
            ps = con.prepareStatement((copyBlob ? BINARY_TRANSIT : BINARY_TRANSIT_FILESYSTEM) + previewSelect
                    + BINARY_TRANSIT_PREVIEW_WHERE);
            ps.setLong(paramIndex++, created.getId());
            ps.setInt(paramIndex++, created.getVersion()); //version
            ps.setInt(paramIndex++, created.getQuality()); //quality
        }
        File binaryTransit = null;
        boolean removeTransitFile = false;
        if (dbTransit) {
            //transit is handled in the database
            try {
                if (!dbStorage) {
                    //binaries are stored on the filesystem
                    binaryTransit = getBinaryTransitFileInfo(binary).getBinaryTransitFile();
                    removeTransitFile = true; //have to clean up afterwards since its a temporary file we get
                }
            } catch (FxApplicationException e) {
                if (e instanceof FxDbException)
                    throw (FxDbException) e;
                throw new FxDbException(e);
            }
        } else {
            //transit file resides on the local file system
            binaryTransit = FxBinaryUtils.getTransitFile(divisionId, binary.getHandle());
            removeTransitFile = true; // temporary transit file can be removed as well
            if (binaryTransit == null)
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
        }

        boolean needExplicitBlobInsert = false;
        if (copyBlob && replaceBinary)
            ps.setString(paramIndex++, binary.getHandle());
        if (!copyBlob) {
            //we do not perform a simple blob copy operation in the database
            if (dbStorage) {
                //binary is stored in the database -> copy it from the transit file (might be a temp. file)
                if (blobInsertSelectAllowed()) {
                    fis = new FileInputStream(binaryTransit);
                    ps.setBinaryStream(paramIndex++, fis, (int) binaryTransit.length());
                } else {
                    ps.setNull(paramIndex++, Types.BINARY);
                    needExplicitBlobInsert = true;
                }
            } else {
                //binary is stored on the filesystem -> move transit file to binary storage file
                try {
                    if (!FxFileUtils.moveFile(binaryTransit,
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.ORIGINAL.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed", created.getId());
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError", created.getId(),
                            e.getMessage());
                }
                ps.setNull(paramIndex++, Types.BINARY);
            }
        }

        //            int cnt = paramIndex; //copyBlob ? 4 : 5;
        ps.setString(paramIndex++, created.getName());
        ps.setLong(paramIndex++, created.getSize());
        setBigString(ps, paramIndex++, created.getMetadata());
        ps.setString(paramIndex++, created.getMimeType());
        if (replaceBinary)
            ps.setNull(paramIndex++, java.sql.Types.NUMERIC); //set preview ref to null
        ps.setBoolean(paramIndex++, created.isImage());
        ps.setDouble(paramIndex++, created.getResolution());
        ps.setInt(paramIndex++, created.getWidth());
        ps.setInt(paramIndex++, created.getHeight());
        ps.setString(paramIndex++, created.getMd5sum());
        if (replaceBinary) {
            ps.setLong(paramIndex++, created.getId());
            ps.setInt(paramIndex++, created.getVersion()); //version
            ps.setInt(paramIndex, created.getQuality()); //quality
        } else
            ps.setString(paramIndex, binary.getHandle());
        ps.executeUpdate();
        if (needExplicitBlobInsert) {
            ps.close();
            ps = con.prepareStatement(
                    "UPDATE " + TBL_CONTENT_BINARY + " SET FBLOB=? WHERE ID=? AND VER=? AND QUALITY=?");
            fis = new FileInputStream(binaryTransit);
            ps.setBinaryStream(1, fis, (int) binaryTransit.length());
            ps.setLong(2, created.getId());
            ps.setInt(3, created.getVersion()); //version
            ps.setInt(4, created.getQuality()); //quality
            ps.executeUpdate();
        }
        if (removeTransitFile && binaryTransit != null) {
            //transit file was a temp. file -> got to clean up
            FxFileUtils.removeFile(binaryTransit);
        }

        if (replaceBinary) {
            ps.close();
            //set all preview entries to the values provided by the transit table
            ps = con.prepareStatement("UPDATE " + TBL_CONTENT_BINARY
                    + " SET PREV1=NULL,PREV2=NULL,PREV3=NULL,PREV4=NULL WHERE ID=? AND VER=? AND QUALITY=?");
            ps.setLong(1, created.getId());
            ps.setInt(2, created.getVersion()); //version
            ps.setInt(3, created.getQuality()); //quality
            ps.executeUpdate();
            ps.close();
            ps = con.prepareStatement(
                    "SELECT PREV1_WIDTH,PREV1_HEIGHT,PREV1SIZE,PREV2_WIDTH,PREV2_HEIGHT,PREV2SIZE,PREV3_WIDTH,PREV3_HEIGHT,PREV3SIZE,PREV4_WIDTH,PREV4_HEIGHT,PREV4SIZE FROM "
                            + TBL_BINARY_TRANSIT + " WHERE BKEY=?");
            ps.setString(1, binary.getHandle());
            ResultSet rsPrev = ps.executeQuery();
            if (rsPrev != null && rsPrev.next()) {
                long[] data = new long[12];
                for (int d = 0; d < 12; d++)
                    data[d] = rsPrev.getLong(d + 1);
                ps.close();
                ps = con.prepareStatement("UPDATE " + TBL_CONTENT_BINARY
                        + " SET PREV1_WIDTH=?,PREV1_HEIGHT=?,PREV1SIZE=?,PREV2_WIDTH=?,PREV2_HEIGHT=?,PREV2SIZE=?,PREV3_WIDTH=?,PREV3_HEIGHT=?,PREV3SIZE=?,PREV4_WIDTH=?,PREV4_HEIGHT=?,PREV4SIZE=? WHERE ID=? AND VER=? AND QUALITY=?");
                for (int d = 0; d < 12; d++)
                    ps.setLong(d + 1, data[d]);
                ps.setLong(13, created.getId());
                ps.setInt(14, created.getVersion()); //version
                ps.setInt(15, created.getQuality()); //quality
                ps.executeUpdate();
            }
        }

        //finally fetch the preview blobs from transit and store them on the filesystem if required
        if (storePrev1FS || storePrev2FS || storePrev3FS || storePrev4FS) {
            ps.close();
            previewSelect = (!storePrev1FS ? ",NULL" : ",PREV1") + (!storePrev2FS ? ",NULL" : ",PREV2")
                    + (!storePrev3FS ? ",NULL" : ",PREV3") + (!storePrev4FS ? ",NULL" : ",PREV4");
            ps = con.prepareStatement("SELECT " + previewSelect.substring(1) + BINARY_TRANSIT_PREVIEW_WHERE);
            ps.setString(1, binary.getHandle());
            ResultSet rs = ps.executeQuery();
            if (!rs.next())
                throw new FxDbException("ex.content.binary.transitNotFound", binary.getHandle());
            if (storePrev1FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev1Length, rs.getBinaryStream(1),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW1.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW1.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW1.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev2FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev2Length, rs.getBinaryStream(2),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW2.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW2.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW2.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev3FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev3Length, rs.getBinaryStream(3),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.PREVIEW3.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.PREVIEW3.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.PREVIEW3.getBlobIndex() + "]", e.getMessage());
                }
            if (storePrev4FS)
                try {
                    if (!FxFileUtils.copyStream2File(prev4Length, rs.getBinaryStream(4),
                            FxBinaryUtils.createBinaryFile(divisionId, created.getId(), created.getVersion(),
                                    created.getQuality(), PreviewSizes.SCREENVIEW.getBlobIndex())))
                        throw new FxDbException(LOG, "ex.content.binary.fsCopyFailed",
                                created.getId() + "[" + PreviewSizes.SCREENVIEW.getBlobIndex() + "]");
                } catch (IOException e) {
                    throw new FxDbException(LOG, "ex.content.binary.fsCopyFailedError",
                            created.getId() + "[" + PreviewSizes.SCREENVIEW.getBlobIndex() + "]",
                            e.getMessage());
                }
        }
        con.commit();
    } catch (SQLException e) {
        throw new FxDbException(e, "ex.db.sqlError", e.getMessage());
    } catch (FileNotFoundException e) {
        throw new FxDbException(e, "ex.content.binary.IOError", binary.getHandle());
    } finally {
        Database.closeObjects(GenericBinarySQLStorage.class, con, ps);
        FxSharedUtils.close(fis);
    }
    return created;
}

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  w ww . j  a  v a2 s  . co  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:com.flexive.core.storage.GenericDivisionImporter.java

/**
 * Import data from a zip archive to a database table
 *
 * @param stmt               statement to use
 * @param zip                zip archive containing the zip entry
 * @param ze                 zip entry within the archive
 * @param xpath              xpath containing the entries to import
 * @param table              name of the table
 * @param executeInsertPhase execute the insert phase?
 * @param executeUpdatePhase execute the update phase?
 * @param updateColumns      columns that should be set to <code>null</code> in a first pass (insert)
 *                           and updated to the provided values in a second pass (update),
 *                           columns that should be used in the where clause have to be prefixed
 *                           with "KEY:", to assign a default value use the expression "columnname:default value",
 *                           if the default value is "@", it will be a negative counter starting at 0, decreasing.
 *                           If the default value starts with "%", it will be set to the column following the "%"
 *                           character in the first pass
 * @throws Exception on errors//from w w w  .  j av a  2s .  c  o  m
 */
protected void importTable(Statement stmt, final ZipFile zip, final ZipEntry ze, final String xpath,
        final String table, final boolean executeInsertPhase, final boolean executeUpdatePhase,
        final String... updateColumns) throws Exception {
    //analyze the table
    final ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " WHERE 1=2");
    StringBuilder sbInsert = new StringBuilder(500);
    StringBuilder sbUpdate = updateColumns.length > 0 ? new StringBuilder(500) : null;
    if (rs == null)
        throw new IllegalArgumentException("Can not analyze table [" + table + "]!");
    sbInsert.append("INSERT INTO ").append(table).append(" (");
    final ResultSetMetaData md = rs.getMetaData();
    final Map<String, ColumnInfo> updateClauseColumns = updateColumns.length > 0
            ? new HashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, ColumnInfo> updateSetColumns = updateColumns.length > 0
            ? new LinkedHashMap<String, ColumnInfo>(md.getColumnCount())
            : null;
    final Map<String, String> presetColumns = updateColumns.length > 0 ? new HashMap<String, String>(10) : null;
    //preset to a referenced column (%column syntax)
    final Map<String, String> presetRefColumns = updateColumns.length > 0 ? new HashMap<String, String>(10)
            : null;
    final Map<String, Integer> counters = updateColumns.length > 0 ? new HashMap<String, Integer>(10) : null;
    final Map<String, ColumnInfo> insertColumns = new HashMap<String, ColumnInfo>(
            md.getColumnCount() + (counters != null ? counters.size() : 0));
    int insertIndex = 1;
    int updateSetIndex = 1;
    int updateClauseIndex = 1;
    boolean first = true;
    for (int i = 0; i < md.getColumnCount(); i++) {
        final String currCol = md.getColumnName(i + 1).toLowerCase();
        if (updateColumns.length > 0) {
            boolean abort = false;
            for (String col : updateColumns) {
                if (col.indexOf(':') > 0 && !col.startsWith("KEY:")) {
                    String value = col.substring(col.indexOf(':') + 1);
                    col = col.substring(0, col.indexOf(':'));
                    if ("@".equals(value)) {
                        if (currCol.equalsIgnoreCase(col)) {
                            counters.put(col, 0);
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                        }
                    } else if (value.startsWith("%")) {
                        if (currCol.equalsIgnoreCase(col)) {
                            presetRefColumns.put(col, value.substring(1));
                            insertColumns.put(col, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
                            sbInsert.append(',').append(currCol);
                            //                                System.out.println("==> adding presetRefColumn "+col+" with value of "+value.substring(1));
                        }
                    } else if (!presetColumns.containsKey(col))
                        presetColumns.put(col, value);
                }
                if (currCol.equalsIgnoreCase(col)) {
                    abort = true;
                    updateSetColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), updateSetIndex++));
                    break;
                }
            }
            if (abort)
                continue;
        }
        if (first) {
            first = false;
        } else
            sbInsert.append(',');
        sbInsert.append(currCol);
        insertColumns.put(currCol, new ColumnInfo(md.getColumnType(i + 1), insertIndex++));
    }
    if (updateColumns.length > 0 && executeUpdatePhase) {
        sbUpdate.append("UPDATE ").append(table).append(" SET ");
        int counter = 0;
        for (String updateColumn : updateSetColumns.keySet()) {
            if (counter++ > 0)
                sbUpdate.append(',');
            sbUpdate.append(updateColumn).append("=?");
        }
        sbUpdate.append(" WHERE ");
        boolean hasKeyColumn = false;
        for (String col : updateColumns) {
            if (!col.startsWith("KEY:"))
                continue;
            hasKeyColumn = true;
            String keyCol = col.substring(4);
            for (int i = 0; i < md.getColumnCount(); i++) {
                if (!md.getColumnName(i + 1).equalsIgnoreCase(keyCol))
                    continue;
                updateClauseColumns.put(keyCol, new ColumnInfo(md.getColumnType(i + 1), updateClauseIndex++));
                sbUpdate.append(keyCol).append("=? AND ");
                break;
            }

        }
        if (!hasKeyColumn)
            throw new IllegalArgumentException("Update columns require a KEY!");
        sbUpdate.delete(sbUpdate.length() - 5, sbUpdate.length()); //remove trailing " AND "
        //"shift" clause indices
        for (String col : updateClauseColumns.keySet()) {
            GenericDivisionImporter.ColumnInfo ci = updateClauseColumns.get(col);
            ci.index += (updateSetIndex - 1);
        }
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(key);
    }
    sbInsert.append(")VALUES(");
    for (int i = 0; i < insertColumns.size(); i++) {
        if (i > 0)
            sbInsert.append(',');
        sbInsert.append('?');
    }
    if (presetColumns != null) {
        for (String key : presetColumns.keySet())
            sbInsert.append(',').append(presetColumns.get(key));
    }
    sbInsert.append(')');
    if (DBG) {
        LOG.info("Insert statement:\n" + sbInsert.toString());
        if (updateColumns.length > 0)
            LOG.info("Update statement:\n" + sbUpdate.toString());
    }
    //build a map containing all nodes that require attributes
    //this allows for matching simple xpath queries like "flatstorages/storage[@name='FX_FLAT_STORAGE']/data"
    final Map<String, List<String>> queryAttributes = new HashMap<String, List<String>>(5);
    for (String pElem : xpath.split("/")) {
        if (!(pElem.indexOf('@') > 0 && pElem.indexOf('[') > 0))
            continue;
        List<String> att = new ArrayList<String>(5);
        for (String pAtt : pElem.split("@")) {
            if (!(pAtt.indexOf('=') > 0))
                continue;
            att.add(pAtt.substring(0, pAtt.indexOf('=')));
        }
        queryAttributes.put(pElem.substring(0, pElem.indexOf('[')), att);
    }
    final PreparedStatement psInsert = stmt.getConnection().prepareStatement(sbInsert.toString());
    final PreparedStatement psUpdate = updateColumns.length > 0 && executeUpdatePhase
            ? stmt.getConnection().prepareStatement(sbUpdate.toString())
            : null;
    try {
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final DefaultHandler handler = new DefaultHandler() {
            private String currentElement = null;
            private Map<String, String> data = new HashMap<String, String>(10);
            private StringBuilder sbData = new StringBuilder(10000);
            boolean inTag = false;
            boolean inElement = false;
            int counter;
            List<String> path = new ArrayList<String>(10);
            StringBuilder currPath = new StringBuilder(100);
            boolean insertMode = true;

            /**
             * {@inheritDoc}
             */
            @Override
            public void startDocument() throws SAXException {
                counter = 0;
                inTag = false;
                inElement = false;
                path.clear();
                currPath.setLength(0);
                sbData.setLength(0);
                data.clear();
                currentElement = null;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void processingInstruction(String target, String data) throws SAXException {
                if (target != null && target.startsWith("fx_")) {
                    if (target.equals("fx_mode"))
                        insertMode = "insert".equals(data);
                } else
                    super.processingInstruction(target, data);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endDocument() throws SAXException {
                if (insertMode)
                    LOG.info("Imported [" + counter + "] entries into [" + table + "] for xpath [" + xpath
                            + "]");
                else
                    LOG.info("Updated [" + counter + "] entries in [" + table + "] for xpath [" + xpath + "]");
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                pushPath(qName, attributes);
                if (currPath.toString().equals(xpath)) {
                    inTag = true;
                    data.clear();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        String name = attributes.getLocalName(i);
                        if (StringUtils.isEmpty(name))
                            name = attributes.getQName(i);
                        data.put(name, attributes.getValue(i));
                    }
                } else {
                    currentElement = qName;
                }
                inElement = true;
                sbData.setLength(0);
            }

            /**
             * Push a path element from the stack
             *
             * @param qName element name to push
             * @param att attributes
             */
            private void pushPath(String qName, Attributes att) {
                if (att.getLength() > 0 && queryAttributes.containsKey(qName)) {
                    String curr = qName + "[";
                    boolean first = true;
                    final List<String> attList = queryAttributes.get(qName);
                    for (int i = 0; i < att.getLength(); i++) {
                        if (!attList.contains(att.getQName(i)))
                            continue;
                        if (first)
                            first = false;
                        else
                            curr += ',';
                        curr += "@" + att.getQName(i) + "='" + att.getValue(i) + "'";
                    }
                    curr += ']';
                    path.add(curr);
                } else
                    path.add(qName);
                buildPath();
            }

            /**
             * Pop the top path element from the stack
             */
            private void popPath() {
                path.remove(path.size() - 1);
                buildPath();
            }

            /**
             * Rebuild the current path
             */
            private synchronized void buildPath() {
                currPath.setLength(0);
                for (String s : path)
                    currPath.append(s).append('/');
                if (currPath.length() > 1)
                    currPath.delete(currPath.length() - 1, currPath.length());
                //                    System.out.println("currPath: " + currPath);
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (currPath.toString().equals(xpath)) {
                    if (DBG)
                        LOG.info("Insert [" + xpath + "]: [" + data + "]");
                    inTag = false;
                    try {
                        if (insertMode) {
                            if (executeInsertPhase) {
                                processColumnSet(insertColumns, psInsert);
                                counter += psInsert.executeUpdate();
                            }
                        } else {
                            if (executeUpdatePhase) {
                                if (processColumnSet(updateSetColumns, psUpdate)) {
                                    processColumnSet(updateClauseColumns, psUpdate);
                                    counter += psUpdate.executeUpdate();
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new SAXException(e);
                    } catch (ParseException e) {
                        throw new SAXException(e);
                    }
                } else {
                    if (inTag) {
                        data.put(currentElement, sbData.toString());
                    }
                    currentElement = null;
                }
                popPath();
                inElement = false;
                sbData.setLength(0);
            }

            /**
             * Process a column set
             *
             * @param columns the columns to process
             * @param ps prepared statement to use
             * @return if data other than <code>null</code> has been set
             * @throws SQLException on errors
             * @throws ParseException on date/time conversion errors
             */
            private boolean processColumnSet(Map<String, ColumnInfo> columns, PreparedStatement ps)
                    throws SQLException, ParseException {
                boolean dataSet = false;
                for (String col : columns.keySet()) {
                    ColumnInfo ci = columns.get(col);
                    String value = data.get(col);
                    if (insertMode && counters != null && counters.get(col) != null) {
                        final int newVal = counters.get(col) - 1;
                        value = String.valueOf(newVal);
                        counters.put(col, newVal);
                        //                            System.out.println("new value for " + col + ": " + newVal);
                    }
                    if (insertMode && presetRefColumns != null && presetRefColumns.get(col) != null) {
                        value = data.get(presetRefColumns.get(col));
                        //                            System.out.println("Set presetRefColumn for "+col+" to ["+value+"] from column ["+presetRefColumns.get(col)+"]");
                    }

                    if (value == null)
                        ps.setNull(ci.index, ci.columnType);
                    else {
                        dataSet = true;
                        switch (ci.columnType) {
                        case Types.BIGINT:
                        case Types.NUMERIC:
                            if (DBG)
                                LOG.info("BigInt " + ci.index + "->" + new BigDecimal(value));
                            ps.setBigDecimal(ci.index, new BigDecimal(value));
                            break;
                        case java.sql.Types.DOUBLE:
                            if (DBG)
                                LOG.info("Double " + ci.index + "->" + Double.parseDouble(value));
                            ps.setDouble(ci.index, Double.parseDouble(value));
                            break;
                        case java.sql.Types.FLOAT:
                        case java.sql.Types.REAL:
                            if (DBG)
                                LOG.info("Float " + ci.index + "->" + Float.parseFloat(value));
                            ps.setFloat(ci.index, Float.parseFloat(value));
                            break;
                        case java.sql.Types.TIMESTAMP:
                        case java.sql.Types.DATE:
                            if (DBG)
                                LOG.info("Timestamp/Date " + ci.index + "->"
                                        + FxFormatUtils.getDateTimeFormat().parse(value));
                            ps.setTimestamp(ci.index,
                                    new Timestamp(FxFormatUtils.getDateTimeFormat().parse(value).getTime()));
                            break;
                        case Types.TINYINT:
                        case Types.SMALLINT:
                            if (DBG)
                                LOG.info("Integer " + ci.index + "->" + Integer.valueOf(value));
                            ps.setInt(ci.index, Integer.valueOf(value));
                            break;
                        case Types.INTEGER:
                        case Types.DECIMAL:
                            try {
                                if (DBG)
                                    LOG.info("Long " + ci.index + "->" + Long.valueOf(value));
                                ps.setLong(ci.index, Long.valueOf(value));
                            } catch (NumberFormatException e) {
                                //Fallback (temporary) for H2 if the reported long is a big decimal (tree...)
                                ps.setBigDecimal(ci.index, new BigDecimal(value));
                            }
                            break;
                        case Types.BIT:
                        case Types.CHAR:
                        case Types.BOOLEAN:
                            if (DBG)
                                LOG.info("Boolean " + ci.index + "->" + value);
                            if ("1".equals(value) || "true".equals(value))
                                ps.setBoolean(ci.index, true);
                            else
                                ps.setBoolean(ci.index, false);
                            break;
                        case Types.LONGVARBINARY:
                        case Types.VARBINARY:
                        case Types.BLOB:
                        case Types.BINARY:
                            ZipEntry bin = zip.getEntry(value);
                            if (bin == null) {
                                LOG.error("Failed to lookup binary [" + value + "]!");
                                ps.setNull(ci.index, ci.columnType);
                                break;
                            }
                            try {
                                ps.setBinaryStream(ci.index, zip.getInputStream(bin), (int) bin.getSize());
                            } catch (IOException e) {
                                LOG.error("IOException importing binary [" + value + "]: " + e.getMessage(), e);
                            }
                            break;
                        case Types.CLOB:
                        case Types.LONGVARCHAR:
                        case Types.VARCHAR:
                        case SQL_LONGNVARCHAR:
                        case SQL_NCHAR:
                        case SQL_NCLOB:
                        case SQL_NVARCHAR:
                            if (DBG)
                                LOG.info("String " + ci.index + "->" + value);
                            ps.setString(ci.index, value);
                            break;
                        default:
                            LOG.warn("Unhandled type [" + ci.columnType + "] for column [" + col + "]");
                        }
                    }
                }
                return dataSet;
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (inElement)
                    sbData.append(ch, start, length);
            }

        };
        handler.processingInstruction("fx_mode", "insert");
        parser.parse(zip.getInputStream(ze), handler);
        if (updateColumns.length > 0 && executeUpdatePhase) {
            handler.processingInstruction("fx_mode", "update");
            parser.parse(zip.getInputStream(ze), handler);
        }
    } finally {
        Database.closeObjects(GenericDivisionImporter.class, psInsert, psUpdate);
    }
}

From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java

public boolean setHibernateType(@Nullable SimpleValue value,
        com.manydesigns.portofino.model.database.Column column, Class javaType, final int jdbcType) {
    String typeName;/*from ww  w  .jav  a  2s  .  c o  m*/
    Properties typeParams = null;
    if (javaType == null) {
        return false;
    }
    if (javaType == Long.class) {
        typeName = LongType.INSTANCE.getName();
    } else if (javaType == Short.class) {
        typeName = ShortType.INSTANCE.getName();
    } else if (javaType == Integer.class) {
        typeName = IntegerType.INSTANCE.getName();
    } else if (javaType == Byte.class) {
        typeName = ByteType.INSTANCE.getName();
    } else if (javaType == Float.class) {
        typeName = FloatType.INSTANCE.getName();
    } else if (javaType == Double.class) {
        typeName = DoubleType.INSTANCE.getName();
    } else if (javaType == Character.class) {
        typeName = CharacterType.INSTANCE.getName();
    } else if (javaType == String.class) {
        typeName = StringType.INSTANCE.getName();
    } else if (java.util.Date.class.isAssignableFrom(javaType)) {
        switch (jdbcType) {
        case Types.DATE:
            typeName = DateType.INSTANCE.getName();
            break;
        case Types.TIME:
            typeName = TimeType.INSTANCE.getName();
            break;
        case Types.TIMESTAMP:
            typeName = TimestampType.INSTANCE.getName();
            break;
        default:
            typeName = null;
        }
    } else if (javaType == Boolean.class) {
        if (jdbcType == Types.BIT || jdbcType == Types.BOOLEAN) {
            typeName = BooleanType.INSTANCE.getName();
        } else if (jdbcType == Types.NUMERIC || jdbcType == Types.DECIMAL || jdbcType == Types.INTEGER
                || jdbcType == Types.SMALLINT || jdbcType == Types.TINYINT || jdbcType == Types.BIGINT) {
            typeName = NumericBooleanType.INSTANCE.getName();
        } else if (jdbcType == Types.CHAR || jdbcType == Types.VARCHAR) {
            typeName = StringBooleanType.class.getName();
            typeParams = new Properties();
            typeParams.setProperty("true", trueString != null ? trueString : StringBooleanType.NULL);
            typeParams.setProperty("false", falseString != null ? falseString : StringBooleanType.NULL);
            typeParams.setProperty("sqlType", String.valueOf(jdbcType));
        } else {
            typeName = null;
        }
    } else if (javaType == BigDecimal.class) {
        typeName = BigDecimalType.INSTANCE.getName();
    } else if (javaType == BigInteger.class) {
        typeName = BigIntegerType.INSTANCE.getName();
    } else if (javaType == byte[].class) {
        typeName = BlobType.INSTANCE.getName();
    } else {
        typeName = null;
    }

    if (typeName == null) {
        logger.error("Unsupported type (java type: {}, jdbc type: {}) " + "for column '{}'.",
                new Object[] { javaType, jdbcType, column.getColumnName() });
        return false;
    }

    if (value != null) {
        value.setTypeName(typeName);
        if (typeParams != null) {
            value.setTypeParameters(typeParams);
        }
    }
    return true;
}