Example usage for java.sql Types TIMESTAMP

List of usage examples for java.sql Types TIMESTAMP

Introduction

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

Prototype

int TIMESTAMP

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

Click Source Link

Document

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

Usage

From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java

public void updateChannel(Channel channel) {
    Connection conn = null;/*w w  w  . ja v  a 2  s  .  c  o m*/
    PreparedStatement ps = null;

    try {
        conn = DriverManager.getConnection(JdbcChannelDAO.POOL_CONNECT_STRING);
        ps = conn.prepareStatement("UPDATE " + TABLE_CHANNELS + " " + "SET author = ?, name = ?, url = ?, "
                + "title = ?, link = ?, description = ?, " + "lastArticle = ?, "
                + "lastPolled = ?, lastCleaned = ?, lastModified = ?, lastETag = ?, rssVersion = ?, "
                + "enabled = ?, " + "postingEnabled = ?, " + "publishAPI = ?, " + "publishConfig = ?, "
                + "parseAtAllCost = ?, " + "managingEditor = ?, " + "pollingInterval = ?, " + "status = ?, "
                + "expiration = ?, " + "category = ? " + "WHERE id = ?");

        int paramCount = 1;
        ps.setString(paramCount++, trim(channel.getAuthor(), FIELD_CHANNEL_AUTHOR_LENGTH));
        ps.setString(paramCount++, trim(channel.getName(), FIELD_CHANNEL_NAME_LENGTH));
        ps.setString(paramCount++, channel.getUrl());
        ps.setString(paramCount++, trim(channel.getTitle(), FIELD_CHANNEL_TITLE_LENGTH));
        ps.setString(paramCount++, channel.getLink());
        ps.setString(paramCount++, channel.getDescription());
        ps.setInt(paramCount++, channel.getLastArticleNumber());

        if (channel.getLastPolled() != null) {
            ps.setTimestamp(paramCount++, new Timestamp(channel.getLastPolled().getTime()));
        } else {
            ps.setNull(paramCount++, java.sql.Types.TIMESTAMP);
        }

        if (channel.getLastCleaned() != null) {
            ps.setTimestamp(paramCount++, new Timestamp(channel.getLastCleaned().getTime()));
        } else {
            ps.setNull(paramCount++, java.sql.Types.TIMESTAMP);
        }

        ps.setLong(paramCount++, channel.getLastModified());
        ps.setString(paramCount++, channel.getLastETag());
        ps.setString(paramCount++, trim(channel.getRssVersion(), FIELD_CHANNEL_VERSION_LENGTH));
        //                  ps.setBoolean(paramCount++, channel.isHistorical());
        ps.setBoolean(paramCount++, channel.isEnabled());
        ps.setBoolean(paramCount++, channel.isPostingEnabled());
        ps.setString(paramCount++, channel.getPublishAPI());
        ps.setString(paramCount++, XMLHelper.stringMapToXML(channel.getPublishConfig()));
        ps.setBoolean(paramCount++, channel.isParseAtAllCost());

        ps.setString(paramCount++, trim(channel.getManagingEditor(), FIELD_CHANNEL_MANAGING_EDITOR_LENGTH));

        ps.setLong(paramCount++, channel.getPollingIntervalSeconds());
        ps.setInt(paramCount++, channel.getStatus());
        ps.setLong(paramCount++, channel.getExpiration());
        int categoryId = 0;
        if (channel.getCategory() != null) {
            categoryId = channel.getCategory().getId();
        }
        ps.setInt(paramCount++, categoryId);

        ps.setInt(paramCount++, channel.getId());
        ps.executeUpdate();

    } catch (SQLException se) {
        throw new RuntimeException(se);
    } finally {
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException se) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
        }
    }

}

From source file:com.splicemachine.db.impl.sql.compile.QueryTreeNode.java

/**
 * Get a ConstantNode to represent a typed null value.
 *
 * @param type Type of the null node.//from  ww  w  .ja va 2s  .co  m
 * @throws StandardException Thrown on error
 * @return A ConstantNode with the specified type, and a value of null
 */
public ConstantNode getNullNode(DataTypeDescriptor type) throws StandardException {
    int constantNodeType;
    switch (type.getTypeId().getJDBCTypeId()) {
    case Types.VARCHAR:
        constantNodeType = C_NodeTypes.VARCHAR_CONSTANT_NODE;
        break;
    case Types.CHAR:
        constantNodeType = C_NodeTypes.CHAR_CONSTANT_NODE;
        break;
    case Types.TINYINT:
        constantNodeType = C_NodeTypes.TINYINT_CONSTANT_NODE;
        break;
    case Types.SMALLINT:
        constantNodeType = C_NodeTypes.SMALLINT_CONSTANT_NODE;
        break;
    case Types.INTEGER:
        constantNodeType = C_NodeTypes.INT_CONSTANT_NODE;
        break;
    case Types.BIGINT:
        constantNodeType = C_NodeTypes.LONGINT_CONSTANT_NODE;
        break;
    case Types.REAL:
        constantNodeType = C_NodeTypes.FLOAT_CONSTANT_NODE;
        break;
    case Types.DOUBLE:
        constantNodeType = C_NodeTypes.DOUBLE_CONSTANT_NODE;
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        constantNodeType = C_NodeTypes.DECIMAL_CONSTANT_NODE;
        break;
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        constantNodeType = C_NodeTypes.USERTYPE_CONSTANT_NODE;
        break;
    case Types.BINARY:
        constantNodeType = C_NodeTypes.BIT_CONSTANT_NODE;
        break;
    case Types.VARBINARY:
        constantNodeType = C_NodeTypes.VARBIT_CONSTANT_NODE;
        break;
    case Types.LONGVARCHAR:
        constantNodeType = C_NodeTypes.LONGVARCHAR_CONSTANT_NODE;
        break;
    case Types.CLOB:
        constantNodeType = C_NodeTypes.CLOB_CONSTANT_NODE;
        break;
    case Types.LONGVARBINARY:
        constantNodeType = C_NodeTypes.LONGVARBIT_CONSTANT_NODE;
        break;
    case Types.BLOB:
        constantNodeType = C_NodeTypes.BLOB_CONSTANT_NODE;
        break;
    case JDBC40Translation.SQLXML:
        constantNodeType = C_NodeTypes.XML_CONSTANT_NODE;
        break;
    case Types.BOOLEAN:
        constantNodeType = C_NodeTypes.BOOLEAN_CONSTANT_NODE;
        break;
    default:
        if (type.getTypeId().userType()) {
            constantNodeType = C_NodeTypes.USERTYPE_CONSTANT_NODE;
        } else {
            throw StandardException.newException(SQLState.LANG_NONULL_DATATYPE,
                    type.getTypeId().getSQLTypeName());
        }
    }

    ConstantNode constantNode = (ConstantNode) getNodeFactory().getNode(constantNodeType, type.getTypeId(), cm);

    constantNode.setType(type.getNullabilityType(true));

    return constantNode;
}

From source file:com.funambol.foundation.items.dao.PIMCalendarDAO.java

/**
 * Adds a calendar. If necessary, a new ID is generated and set in the
 * CalendarWrapper./*from w w  w  . j  av  a 2s. c om*/
 *
 * @param c as a CalendarWrapper object, usually without an ID set.
 * @throws DAOException
 *
 * @see CalendarWrapper
 */
public void addItem(CalendarWrapper cw) throws DAOException {

    if (log.isTraceEnabled()) {
        log.trace("PIMCalendarDAO addItem begin");
    }

    Connection con = null;
    PreparedStatement ps = null;

    long id = 0;
    String allDay = null;
    String body = null;
    Short busyStatus = null;
    String categories = null;
    String companies = null;
    int duration = 0;
    Date dend = null;
    short importance = 0;
    String location = null;
    Short meetingStatus = null;
    String mileage = null;
    Date replyTime = null;
    short sensitivity = 0;
    Date dstart = null;
    String subject = null;
    int interval = 0;
    short monthOfYear = 0;
    short dayOfMonth = 0;
    String dayOfWeekMask = null;
    short instance = 0;
    String startDatePattern = null;
    String endDatePattern = null;
    Reminder reminder = null;
    RecurrencePattern rp = null;
    short recurrenceType = -1;
    String sId = null;
    int occurrences = -1;
    String folder = null;
    String dstartTimeZone = null;
    String dendTimeZone = null;
    String reminderTimeZone = null;
    Date completed = null;
    short percentComplete = -1;

    Timestamp lastUpdate = cw.getLastUpdate();
    if (lastUpdate == null) {
        lastUpdate = new Timestamp(System.currentTimeMillis());
    }

    try {

        sId = cw.getId();
        if (sId == null || sId.length() == 0) { // ...as it should be
            sId = getNextID();
            cw.setId(sId);
        }
        id = Long.parseLong(sId);

        CalendarContent c = cw.getCalendar().getCalendarContent();

        rp = c.getRecurrencePattern();

        boolean allDayB;
        if (c.getAllDay() != null && c.getAllDay().booleanValue()) {
            allDayB = true;
            allDay = "1";
        } else {
            allDayB = false;
            allDay = "0";
        }

        String sd = null;
        if (c.getDtStart() != null) {
            sd = c.getDtStart().getPropertyValueAsString();
            dstart = getDateFromString(allDayB, sd, "000000");
        }

        String ed = null;
        if ((sd != null && sd.length() > 0) || c.getDtEnd() != null) {
            ed = c.getDtEnd().getPropertyValueAsString();

            //
            // Fix for Siemens S56 end date issue only for event
            // @todo: verify if is really need to do this
            //
            if (c instanceof Event) {
                if (ed == null || ed.length() == 0) {
                    ed = sd;
                }
            }

            dend = getDateFromString(allDayB, ed, "235900");
        }

        body = Property.stringFrom(c.getDescription());

        if (c.getBusyStatus() != null) {
            busyStatus = new Short(c.getBusyStatus().shortValue());
        }

        categories = Property.stringFrom(c.getCategories());
        companies = Property.stringFrom(c.getOrganizer());
        location = Property.stringFrom(c.getLocation());
        folder = Property.stringFrom(c.getFolder());
        dstartTimeZone = timeZoneFrom(c.getDtStart());
        dendTimeZone = timeZoneFrom(c.getDtEnd());
        reminderTimeZone = timeZoneFrom(c.getReminder());
        meetingStatus = c.getMeetingStatus();

        Integer mileageInteger = c.getMileage(); // NB: not an int...
        if (mileageInteger != null) { // ...therefore it may be null
            mileage = String.valueOf(mileageInteger);
        }

        if (c instanceof Event) {
            replyTime = getDateFromString(allDayB, // @todo or false?
                    Property.stringFrom(((Event) c).getReplyTime()), "000000");
        }

        try {
            sensitivity = Short.parseShort(Property.stringFrom(c.getAccessClass()));
        } catch (NumberFormatException nfe) {
            sensitivity = 0;
            // The short must go on
        }

        if ((subject = Property.stringFrom(c.getSummary())) == null && body != null) {
            int endOfSentence = body.indexOf('.');
            if (endOfSentence == -1) {
                endOfSentence = body.length();
            }
            if (endOfSentence > SQL_SUBJECT_DIM) {
                endOfSentence = SQL_SUBJECT_DIM;
            }
            subject = body.substring(0, endOfSentence);
        }

        String isInfinite = "0";
        if (rp != null) {
            interval = rp.getInterval();
            recurrenceType = rp.getTypeId();
            monthOfYear = rp.getMonthOfYear();
            dayOfMonth = rp.getDayOfMonth();
            dayOfWeekMask = String.valueOf(rp.getDayOfWeekMask());
            instance = rp.getInstance();
            startDatePattern = rp.getStartDatePattern();
            endDatePattern = rp.getEndDatePattern();
            if (rp.isNoEndDate()) {
                isInfinite = "1";
            }
            occurrences = rp.getOccurrences();
        }

        if (c instanceof Task) {
            Task t = (Task) c;
            if (t.getDateCompleted() != null) {
                completed = getDateFromString(allDayB, ((Task) c).getDateCompleted().getPropertyValueAsString(),
                        "000000");
            }

            try {
                String complete = Property.stringFrom(t.getComplete());
                if (complete != null && complete.equals("1")) {
                    percentComplete = 100;
                } else {
                    percentComplete = Short.parseShort(Property.stringFrom(t.getPercentComplete()));
                }
                if (percentComplete < 0 || percentComplete > 100) {
                    throw new NumberFormatException("A percentage can't be " + percentComplete);
                }
            } catch (NumberFormatException nfe) {
                percentComplete = -1; // the short must go on
            }

            meetingStatus = getTaskStatus(t);
        }

        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR);

        ps.setLong(1, id);
        ps.setString(2, userId);
        ps.setLong(3, lastUpdate.getTime());
        ps.setString(4, String.valueOf(Def.PIM_STATE_NEW));
        ps.setString(5, allDay);
        ps.setString(6, StringUtils.left(body, SQL_BODY_DIM));
        if (busyStatus != null) {
            ps.setShort(7, busyStatus.shortValue());
        } else {
            ps.setNull(7, Types.SMALLINT);
        }
        ps.setString(8, StringUtils.left(categories, SQL_CATEGORIES_DIM));
        ps.setString(9, StringUtils.left(companies, SQL_COMPANIES_DIM));
        ps.setInt(10, duration);
        if (dend != null) {
            ps.setTimestamp(11, new Timestamp(dend.getTime()));
        } else {
            ps.setNull(11, Types.TIMESTAMP);
        }

        if (c.getPriority() != null) {

            String priority = c.getPriority().getPropertyValueAsString();

            if (priority != null && priority.length() > 0) {
                importance = Short.parseShort(priority);
                ps.setShort(12, importance);
            } else {
                ps.setNull(12, Types.SMALLINT);
            }

        } else {
            ps.setNull(12, Types.SMALLINT);
        }

        ps.setString(13, StringUtils.left(location, SQL_LOCATION_DIM));

        if (meetingStatus != null) {
            ps.setShort(14, meetingStatus.shortValue());
        } else {
            ps.setNull(14, Types.SMALLINT);
        }

        ps.setString(15, mileage);

        reminder = c.getReminder();
        if (reminder != null && reminder.isActive()) {
            Timestamp reminderTime = getReminderTime(dstart, reminder);
            if (reminderTime == null) {
                ps.setNull(16, Types.TIMESTAMP);
            } else {
                ps.setTimestamp(16, reminderTime);
            }
            ps.setInt(17, reminder.getRepeatCount());
            ps.setString(18, (reminder.isActive()) ? "1" : "0");

            String soundFileValue = reminder.getSoundFile();
            ps.setString(19, StringUtils.left(soundFileValue, SQL_SOUNDFILE_DIM));
            ps.setInt(20, reminder.getOptions());
        } else {
            ps.setNull(16, Types.TIMESTAMP);
            ps.setInt(17, 0);
            ps.setString(18, "0");
            ps.setString(19, null);
            ps.setInt(20, 0);
        }

        if (replyTime != null) {
            ps.setTimestamp(21, new Timestamp(replyTime.getTime()));
        } else {
            ps.setNull(21, Types.TIMESTAMP);
        }

        ps.setShort(22, sensitivity);

        if (dstart != null) {
            ps.setTimestamp(23, new Timestamp(dstart.getTime()));
        } else {
            ps.setNull(23, Types.TIMESTAMP);
        }
        ps.setString(24, StringUtils.left(subject, SQL_SUBJECT_DIM));
        ps.setShort(25, recurrenceType);
        ps.setInt(26, interval);
        ps.setShort(27, monthOfYear);
        ps.setShort(28, dayOfMonth);
        ps.setString(29, StringUtils.left(dayOfWeekMask, SQL_DAYOFWEEKMASK_DIM));
        ps.setShort(30, instance);
        ps.setString(31, StringUtils.left(startDatePattern, SQL_STARTDATEPATTERN_DIM));
        ps.setString(32, isInfinite);
        ps.setString(33, StringUtils.left(endDatePattern, SQL_ENDDATEPATTERN_DIM));
        ps.setInt(34, occurrences);

        if (c instanceof Event) {
            ps.setInt(35, CALENDAR_EVENT_TYPE);
            ps.setNull(36, Types.TIMESTAMP); // completed
            ps.setNull(37, Types.SMALLINT); // percent_complete
        } else {
            ps.setInt(35, CALENDAR_TASK_TYPE);

            if (completed != null) {
                ps.setTimestamp(36, new Timestamp(completed.getTime()));
            } else {
                ps.setNull(36, Types.TIMESTAMP);
            }

            if (percentComplete != -1) {
                ps.setShort(37, percentComplete);
            } else {
                ps.setNull(37, Types.SMALLINT);
            }
        }

        ps.setString(38, StringUtils.left(folder, SQL_FOLDER_DIM));
        ps.setString(39, StringUtils.left(dstartTimeZone, SQL_TIME_ZONE_DIM));
        ps.setString(40, StringUtils.left(dendTimeZone, SQL_TIME_ZONE_DIM));
        ps.setString(41, StringUtils.left(reminderTimeZone, SQL_TIME_ZONE_DIM));

        ps.executeUpdate();
        DBTools.close(null, ps, null);

        if (recurrenceType != -1) {
            List<ExceptionToRecurrenceRule> exceptions = rp.getExceptions();
            for (ExceptionToRecurrenceRule etrr : exceptions) {
                ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR_EXCEPTION);

                ps.setLong(1, id);
                ps.setString(2, (etrr.isAddition() ? "1" : "0"));
                ps.setTimestamp(3,
                        new Timestamp(getDateFromString(allDayB, etrr.getDate(), "000000").getTime()));

                ps.executeUpdate();
                DBTools.close(null, ps, null);
            }
        }

    } catch (Exception e) {
        throw new DAOException("Error adding a calendar item: " + e.getMessage(), e);
    } finally {
        DBTools.close(con, ps, null);
    }
}

From source file:com.google.visualization.datasource.util.SqlDataSourceHelper.java

/**
 * Converts the given SQL type to a value type.
 *
 * @param sqlType The sql type to be converted.
 *
 * @return The value type that fits the given sql type.
 *///w  w w  .  j  a  va 2 s. co m
private static ValueType sqlTypeToValueType(int sqlType) {
    ValueType valueType;
    switch (sqlType) {
    case Types.BOOLEAN:
    case Types.BIT: {
        valueType = ValueType.BOOLEAN;
        break;
    }
    case Types.CHAR:
    case Types.VARCHAR:
        valueType = ValueType.TEXT;
        break;
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.BIGINT:
    case Types.TINYINT:
    case Types.REAL:
    case Types.NUMERIC:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.DECIMAL:
        valueType = ValueType.NUMBER;
        break;
    case Types.DATE:
        valueType = ValueType.DATE;
        break;
    case Types.TIME:
        valueType = ValueType.TIMEOFDAY;
        break;
    case Types.TIMESTAMP:
        valueType = ValueType.DATETIME;
        break;
    default:
        valueType = ValueType.TEXT;
        break;
    }
    return valueType;
}

From source file:org.fastcatsearch.datasource.reader.DBReader.java

@Override
public SchemaSetting getAutoGeneratedSchemaSetting() {
    Map<String, String> properties = singleSourceConfig.getProperties();
    String jdbcSourceId = properties.get("jdbcSourceId");
    String dataSQL = properties.get("dataSQL");
    IRService service = ServiceManager.getInstance().getService(IRService.class);
    Connection con = null;// w  w  w. jav a 2  s .  co  m
    PreparedStatement pst = null;
    ResultSet res = null;
    ResultSetMetaData meta = null;
    try {
        JDBCSourceInfo jdbcInfo = service.getJDBCSourceInfo(jdbcSourceId);
        if (jdbcInfo != null) {
            con = getConnection(jdbcInfo);
        }
        logger.trace("get jdbc connection : {}", con);

        if (con != null) {
            logger.trace("executing sql :{}", dataSQL);
            pst = con.prepareStatement(dataSQL);
            pst.setFetchSize(1);
            pst.setMaxRows(1);
            res = pst.executeQuery();
            res.next();
            meta = res.getMetaData();

            SchemaSetting setting = new SchemaSetting();
            PrimaryKeySetting primaryKeySetting = new PrimaryKeySetting();
            List<FieldSetting> fieldSettingList = new ArrayList<FieldSetting>();
            List<AnalyzerSetting> analyzerSetting = new ArrayList<AnalyzerSetting>();
            List<GroupIndexSetting> groupIndexSetting = new ArrayList<GroupIndexSetting>();
            List<IndexSetting> indexSetting = new ArrayList<IndexSetting>();
            List<FieldIndexSetting> fieldIndexSetting = new ArrayList<FieldIndexSetting>();

            logger.trace("columnCount:{}", meta.getColumnCount());

            String tableName = null;

            for (int inx = 0; inx < meta.getColumnCount(); inx++) {
                if (tableName == null) {
                    tableName = meta.getTableName(inx + 1);
                }
                FieldSetting field = new FieldSetting();
                Type type = null;
                int size = 0;
                switch (meta.getColumnType(inx + 1)) {
                case Types.INTEGER:
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.NUMERIC:
                    type = Type.INT;
                    break;
                case Types.BIGINT:
                    type = Type.LONG;
                    break;
                case Types.FLOAT:
                    type = Type.FLOAT;
                    break;
                case Types.DOUBLE:
                    type = Type.DOUBLE;
                    break;
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP:
                    type = Type.DATETIME;
                    break;
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR:
                    type = Type.STRING;
                    break;
                default:
                    type = Type.STRING;
                    break;
                }
                field.setId(meta.getColumnLabel(inx + 1));
                field.setName(field.getId());
                field.setType(type);
                field.setSize(size);
                logger.trace("field add {}", field);
                fieldSettingList.add(field);
            }

            setting.setFieldSettingList(fieldSettingList);
            setting.setPrimaryKeySetting(primaryKeySetting);
            setting.setFieldIndexSettingList(fieldIndexSetting);
            setting.setAnalyzerSettingList(analyzerSetting);
            setting.setGroupIndexSettingList(groupIndexSetting);
            setting.setIndexSettingList(indexSetting);

            return setting;
        }
    } catch (IRException e) {
        logger.error("", e);
    } catch (SQLException e) {
        logger.error("", e);
    } finally {
        if (res != null)
            try {
                res.close();
            } catch (SQLException ignore) {
            }
        if (pst != null)
            try {
                pst.close();
            } catch (SQLException ignore) {
            }
        if (con != null)
            try {
                con.close();
            } catch (SQLException ignore) {
            }
    }
    return null;
}

From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java

/** <p>Executes the specified procedure.
 *
 *  @param  the SQL procedure to execute
 *  @return the query result/*  ww w.j a va 2s.co m*/
 */
public SqlStatementResult execute(DatabaseExecutable databaseExecutable) throws SQLException {

    if (!prepared()) {

        return statementResult;
    }

    ProcedureParameter[] param = databaseExecutable.getParametersArray();
    Arrays.sort(param, new ProcedureParameterSorter());

    String procQuery = null;
    boolean hasOut = false;
    boolean hasParameters = (param != null && param.length > 0);

    List<ProcedureParameter> outs = null;
    List<ProcedureParameter> ins = null;

    if (hasParameters) {

        // split the params into ins and outs
        outs = new ArrayList<ProcedureParameter>();
        ins = new ArrayList<ProcedureParameter>();

        int type = -1;
        for (int i = 0; i < param.length; i++) {
            type = param[i].getType();
            if (type == DatabaseMetaData.procedureColumnIn || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the ins list
                ins.add(param[i]);

            } else if (type == DatabaseMetaData.procedureColumnOut
                    || type == DatabaseMetaData.procedureColumnResult
                    || type == DatabaseMetaData.procedureColumnReturn
                    || type == DatabaseMetaData.procedureColumnUnknown
                    || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the outs list
                outs.add(param[i]);

            }
        }

        char QUESTION_MARK = '?';
        String COMMA = ", ";

        // init the string buffer
        StringBuilder sb = new StringBuilder("{ ");
        if (!outs.isEmpty()) {

            // build the out params place holders
            for (int i = 0, n = outs.size(); i < n; i++) {

                sb.append(QUESTION_MARK);

                if (i < n - 1) {

                    sb.append(COMMA);
                }

            }

            sb.append(" = ");
        }

        sb.append(" call ");

        if (databaseExecutable.supportCatalogOrSchemaInFunctionOrProcedureCalls()) {

            String namePrefix = null;
            if (databaseExecutable.supportCatalogInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getCatalogName();

            }
            if (databaseExecutable.supportSchemaInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getSchemaName();

            }

            if (namePrefix != null) {

                sb.append(namePrefix).append('.');
            }
        }

        sb.append(databaseExecutable.getName()).append("( ");

        // build the ins params place holders
        for (int i = 0, n = ins.size(); i < n; i++) {
            sb.append(QUESTION_MARK);
            if (i < n - 1) {
                sb.append(COMMA);
            }
        }

        sb.append(" ) }");

        // determine if we have out params
        hasOut = !(outs.isEmpty());
        procQuery = sb.toString();
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("{ call ");

        if (databaseExecutable.getSchemaName() != null) {
            sb.append(databaseExecutable.getSchemaName()).append('.');
        }

        sb.append(databaseExecutable.getName()).append("( ) }");

        procQuery = sb.toString();
    }

    //Log.debug(procQuery);

    // null value literal
    String NULL = "null";

    // clear any warnings
    conn.clearWarnings();

    Log.info("Executing: " + procQuery);

    CallableStatement cstmnt = null;
    try {
        // prepare the statement
        cstmnt = conn.prepareCall(procQuery);
        stmnt = cstmnt;
    } catch (SQLException e) {
        handleException(e);
        statementResult.setSqlException(e);
        return statementResult;
    }

    // check if we are passing parameters
    if (hasParameters) {
        // the parameter index counter
        int index = 1;

        // the java.sql.Type value
        int dataType = -1;

        // the parameter input value
        String value = null;

        // register the out params
        for (int i = 0, n = outs.size(); i < n; i++) {
            //Log.debug("setting out at index: " + index);
            cstmnt.registerOutParameter(index, outs.get(i).getDataType());
            index++;
        }

        try {

            // register the in params
            for (int i = 0, n = ins.size(); i < n; i++) {

                ProcedureParameter procedureParameter = ins.get(i);
                value = procedureParameter.getValue();
                dataType = procedureParameter.getDataType();

                // try infer a type if OTHER
                if (dataType == Types.OTHER) {

                    // checking only for bit/bool for now

                    if (isTrueFalse(value)) {

                        dataType = Types.BOOLEAN;

                    } else if (isBit(value)) {

                        dataType = Types.BIT;
                        value = value.substring(2, value.length() - 1);
                    }

                }

                if (MiscUtils.isNull(value) || value.equalsIgnoreCase(NULL)) {

                    cstmnt.setNull(index, dataType);

                } else {

                    switch (dataType) {

                    case Types.TINYINT:
                        byte _byte = Byte.valueOf(value).byteValue();
                        cstmnt.setShort(index, _byte);
                        break;

                    case Types.SMALLINT:
                        short _short = Short.valueOf(value).shortValue();
                        cstmnt.setShort(index, _short);
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        cstmnt.setString(index, value);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:

                        boolean _boolean = false;
                        if (NumberUtils.isNumber(value)) {

                            int number = Integer.valueOf(value);
                            if (number > 0) {

                                _boolean = true;
                            }

                        } else {

                            _boolean = Boolean.valueOf(value).booleanValue();
                        }

                        cstmnt.setBoolean(index, _boolean);
                        break;

                    case Types.BIGINT:
                        long _long = Long.valueOf(value).longValue();
                        cstmnt.setLong(index, _long);
                        break;

                    case Types.INTEGER:
                        int _int = Integer.valueOf(value).intValue();
                        cstmnt.setInt(index, _int);
                        break;

                    case Types.REAL:
                        float _float = Float.valueOf(value).floatValue();
                        cstmnt.setFloat(index, _float);
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        cstmnt.setBigDecimal(index, new BigDecimal(value));
                        break;
                    /*
                                      case Types.DATE:
                                      case Types.TIMESTAMP:
                                      case Types.TIME:
                                        cstmnt.setTimestamp(index, new Timestamp( BigDecimal(value));
                    */
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        double _double = Double.valueOf(value).doubleValue();
                        cstmnt.setDouble(index, _double);
                        break;

                    default:
                        cstmnt.setObject(index, value);

                    }

                }

                // increment the index
                index++;
            }

        } catch (Exception e) {

            statementResult.setOtherErrorMessage(e.getClass().getName() + ": " + e.getMessage());
            return statementResult;
        }

    }

    /*
    test creating function for postgres:
            
    CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
    RETURNS text
    AS
    $$
     SELECT CASE
        WHEN $3 THEN UPPER($1 || ' ' || $2)
        ELSE LOWER($1 || ' ' || $2)
        END;
    $$
    LANGUAGE SQL IMMUTABLE STRICT;
    */

    try {
        cstmnt.clearWarnings();
        boolean hasResultSet = cstmnt.execute();
        Map<String, Object> results = new HashMap<String, Object>();

        if (hasOut) {
            // incrementing index
            int index = 1;

            // return value from each registered out
            String returnValue = null;

            for (int i = 0; i < param.length; i++) {

                int type = param[i].getType();
                int dataType = param[i].getDataType();

                if (type == DatabaseMetaData.procedureColumnOut
                        || type == DatabaseMetaData.procedureColumnResult
                        || type == DatabaseMetaData.procedureColumnReturn
                        || type == DatabaseMetaData.procedureColumnUnknown
                        || type == DatabaseMetaData.procedureColumnInOut) {

                    switch (dataType) {

                    case Types.TINYINT:
                        returnValue = Byte.toString(cstmnt.getByte(index));
                        break;

                    case Types.SMALLINT:
                        returnValue = Short.toString(cstmnt.getShort(index));
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        returnValue = cstmnt.getString(index);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:
                        returnValue = Boolean.toString(cstmnt.getBoolean(index));
                        break;

                    case Types.INTEGER:
                        returnValue = Integer.toString(cstmnt.getInt(index));
                        break;

                    case Types.BIGINT:
                        returnValue = Long.toString(cstmnt.getLong(index));
                        break;

                    case Types.REAL:
                        returnValue = Float.toString(cstmnt.getFloat(index));
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        returnValue = cstmnt.getBigDecimal(index).toString();
                        break;

                    case Types.DATE:
                    case Types.TIME:
                    case Types.TIMESTAMP:
                        returnValue = cstmnt.getDate(index).toString();
                        break;

                    case Types.FLOAT:
                    case Types.DOUBLE:
                        returnValue = Double.toString(cstmnt.getDouble(index));
                        break;

                    }

                    if (returnValue == null) {
                        returnValue = "NULL";
                    }

                    results.put(param[i].getName(), returnValue);
                    index++;
                }

            }

        }

        if (!hasResultSet) {

            statementResult.setUpdateCount(cstmnt.getUpdateCount());

        } else {

            statementResult.setResultSet(cstmnt.getResultSet());
        }

        useCount++;
        statementResult.setOtherResult(results);

    } catch (SQLException e) {

        statementResult.setSqlException(e);

    } catch (Exception e) {

        statementResult.setMessage(e.getMessage());
    }

    return statementResult;
}

From source file:org.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java

/**
 * Extend to set the columns.//from   w ww.  ja  v a 2  s . c o m
 */
@Override
protected void endFieldMapping(FieldMetaData field) throws SAXException {
    // setup columns with cached lob and temporal info
    FieldMapping fm = (FieldMapping) field;
    if (_lob || _temporal != null) {
        int typeCode = fm.isElementCollection() ? fm.getElement().getDeclaredTypeCode()
                : fm.getDeclaredTypeCode();
        Class<?> type = fm.isElementCollection() ? fm.getElement().getDeclaredType() : fm.getDeclaredType();
        if (_cols == null) {
            _cols = new ArrayList<Column>(1);
            _cols.add(new Column());
        }
        for (Column col : _cols) {
            if (_lob && (typeCode == JavaTypes.STRING || type == char[].class || type == Character[].class)) {
                col.setSize(-1);
                col.setType(Types.CLOB);
            } else if (_lob)
                col.setType(Types.BLOB);
            else {
                switch (_temporal) {
                case DATE:
                    col.setType(Types.DATE);
                    break;
                case TIME:
                    col.setType(Types.TIME);
                    break;
                case TIMESTAMP:
                    col.setType(Types.TIMESTAMP);
                    break;
                }
            }
        }
    }

    if (_cols != null) {
        switch (fm.getDeclaredTypeCode()) {
        case JavaTypes.ARRAY:
            Class<?> type = fm.getDeclaredType();
            if (type == byte[].class || type == Byte[].class || type == char[].class
                    || type == Character[].class) {
                fm.getValueInfo().setColumns(_cols);
                break;
            }
            // else no break
        case JavaTypes.COLLECTION:
            if (!fm.getValue().isSerialized()) {
                fm.getElementMapping().getValueInfo().setColumns(_cols);
            } else {
                fm.getValueInfo().setColumns(_cols);
            }
            break;
        case JavaTypes.MAP:
            fm.getElementMapping().getValueInfo().setColumns(_cols);
            break;
        default:
            fm.getValueInfo().setColumns(_cols);
        }
        if (_colTable != null)
            fm.getMappingInfo().setTableIdentifier(DBIdentifier.newTable(_colTable, delimit()));
        setUnique(fm);
    }
    clearColumnInfo();
}

From source file:CSVWriter.java

private String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException {

    String value = "";

    switch (colType) {
    case Types.BIT:
    case Types.JAVA_OBJECT:
        value = handleObject(rs.getObject(colIndex));
        break;//from   w  w  w.j  a  v a2 s  . c  o  m
    case Types.BOOLEAN:
        boolean b = rs.getBoolean(colIndex);
        value = Boolean.valueOf(b).toString();
        break;
    case NCLOB: // todo : use rs.getNClob
    case Types.CLOB:
        Clob c = rs.getClob(colIndex);
        if (c != null) {
            value = read(c);
        }
        break;
    case Types.BIGINT:
        value = handleLong(rs, colIndex);
        break;
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
    case Types.NUMERIC:
        value = handleBigDecimal(rs.getBigDecimal(colIndex));
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        value = handleInteger(rs, colIndex);
        break;
    case Types.DATE:
        value = handleDate(rs, colIndex);
        break;
    case Types.TIME:
        value = handleTime(rs.getTime(colIndex));
        break;
    case Types.TIMESTAMP:
        value = handleTimestamp(rs.getTimestamp(colIndex));
        break;
    case NVARCHAR: // todo : use rs.getNString
    case NCHAR: // todo : use rs.getNString
    case LONGNVARCHAR: // todo : use rs.getNString
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        value = rs.getString(colIndex);
        break;
    default:
        value = "";
    }

    if (value == null) {
        value = "";
    }

    return value;

}

From source file:org.ensembl.healthcheck.util.DBUtils.java

/**
 * Compare a particular column in two ResultSets.
 * /*from w w w  . java2 s.com*/
 * @param rs1
 *            The first ResultSet to compare.
 * @param rs2
 *            The second ResultSet to compare.
 * @param i
 *            The index of the column to compare.
 * @return True if the type and value of the columns match.
 */
public static boolean compareColumns(ResultSet rs1, ResultSet rs2, int i, boolean warnNull) {

    try {

        ResultSetMetaData rsmd = rs1.getMetaData();

        Connection con1 = rs1.getStatement().getConnection();
        Connection con2 = rs2.getStatement().getConnection();

        if (rs1.getObject(i) == null) {
            if (warnNull) {
                logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i)
                        + " in " + DBUtils.getShortDatabaseName(con1));
            }
            return (rs2.getObject(i) == null); // true if both are null
        }
        if (rs2.getObject(i) == null) {
            if (warnNull) {
                logger.fine("Column " + rsmd.getColumnName(i) + " is null in table " + rsmd.getTableName(i)
                        + " in " + DBUtils.getShortDatabaseName(con2));
            }
            return (rs1.getObject(i) == null); // true if both are null
        }

        // Note deliberate early returns for performance reasons
        switch (rsmd.getColumnType(i)) {

        case Types.INTEGER:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.SMALLINT:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.TINYINT:
            return rs1.getInt(i) == rs2.getInt(i);

        case Types.VARCHAR:
            String s1 = rs1.getString(i);
            String s2 = rs2.getString(i);
            // ignore "AUTO_INCREMENT=" part in final part of table
            // definition
            s1 = s1.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
            s2 = s2.replaceAll("AUTO_INCREMENT=[0-9]+ ", "");
            return s1.equals(s2);

        case Types.FLOAT:
            return rs1.getFloat(i) == rs2.getFloat(i);

        case Types.DOUBLE:
            return rs1.getDouble(i) == rs2.getDouble(i);

        case Types.TIMESTAMP:
            return rs1.getTimestamp(i).equals(rs2.getTimestamp(i));

        default:
            // treat everything else as a String (should deal with ENUM and
            // TEXT)
            if (rs1.getString(i) == null || rs2.getString(i) == null) {
                return true; // ????
            } else {
                return rs1.getString(i).equals(rs2.getString(i));
            }

        } // switch

    } catch (SQLException se) {
        throw new SqlUncheckedException("Could not compare two columns sets", se);
    }

}

From source file:org.batoo.jpa.core.jdbc.adapter.JdbcAdaptor.java

/**
 * Returns the data type of the column.//w w  w .  j  a  v  a  2 s.c o  m
 * 
 * @param cd
 *            the column definition
 * @param sqlType
 *            the sql type
 * @return the data type
 * 
 * @since $version
 * @author hceylan
 */
protected String getColumnType(AbstractColumn cd, int sqlType) {
    switch (sqlType) {
    case Types.BLOB:
        return "BLOB(" + cd.getLength() + ")";
    case Types.CLOB:
        return "CLOB(" + cd.getLength() + ")";
    case Types.VARCHAR:
        return "VARCHAR(" + cd.getLength() + ")";
    case Types.TIME:
        return "TIME";
    case Types.DATE:
        return "DATE";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.CHAR:
        return "CHAR";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.TINYINT:
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT" + (cd.getPrecision() > 0 ? "(" + cd.getPrecision() + ")" : "");
    case Types.DOUBLE:
        return "DOUBLE" + (cd.getPrecision() > 0 ? "(" + cd.getPrecision() + ")" : "");
    case Types.DECIMAL:
        return "DECIMAL" + (cd.getPrecision() > 0
                ? "(" + cd.getPrecision() + (cd.getScale() > 0 ? "," + cd.getScale() : "") + ")"
                : "");
    }

    throw new IllegalArgumentException("Unhandled sql type: " + sqlType);
}