Example usage for java.sql Types DATE

List of usage examples for java.sql Types DATE

Introduction

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

Prototype

int DATE

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

Click Source Link

Document

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

Usage

From source file:co.nubetech.apache.hadoop.DataDrivenDBInputFormat.java

/**
 * @return the DBSplitter implementation to use to divide the table/query
 *         into InputSplits.//  w  ww  .j av  a2  s .  c o m
 */
protected DBSplitter getSplitter(int sqlDataType) {
    switch (sqlDataType) {
    case Types.NUMERIC:
    case Types.DECIMAL:
        return new BigDecimalSplitter();

    case Types.BIT:
    case Types.BOOLEAN:
        return new BooleanSplitter();

    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.BIGINT:
        return new IntegerSplitter();

    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
        return new FloatSplitter();

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return new TextSplitter();

    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return new DateSplitter();

    default:
        // TODO: Support BINARY, VARBINARY, LONGVARBINARY, DISTINCT, CLOB,
        // BLOB, ARRAY
        // STRUCT, REF, DATALINK, and JAVA_OBJECT.
        return null;
    }
}

From source file:architecture.ee.web.community.timeline.dao.jdbc.JdbcTimelineDao.java

public void updateTimeline(Timeline timeline) {
    long timelineIdToUse = timeline.getTimelineId();
    if (timelineIdToUse < 1) {
        timelineIdToUse = nextId();//  www  . j  ava 2  s  .c o m
        ((DefaultTimeline) timeline).setTimelineId(timelineIdToUse);
        getJdbcTemplate().update(getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_TIMELINE").getSql(),
                new SqlParameterValue(Types.NUMERIC, timelineIdToUse),
                new SqlParameterValue(Types.NUMERIC, timeline.getObjectType()),
                new SqlParameterValue(Types.NUMERIC, timeline.getObjectId()),
                new SqlParameterValue(Types.VARCHAR, timeline.getHeadline()),
                new SqlParameterValue(Types.VARCHAR, timeline.getBody()),
                new SqlParameterValue(Types.DATE, timeline.getStartDate()),
                new SqlParameterValue(Types.DATE, timeline.getEndDate()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getUrl()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getCaption()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getCredit()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getThumbnailUrl()));
    } else {
        getJdbcTemplate().update(getBoundSql("ARCHITECTURE_COMMUNITY.UPDATE_TIMELINE").getSql(),
                new SqlParameterValue(Types.VARCHAR, timeline.getHeadline()),
                new SqlParameterValue(Types.VARCHAR, timeline.getBody()),
                new SqlParameterValue(Types.DATE, timeline.getStartDate()),
                new SqlParameterValue(Types.DATE, timeline.getEndDate()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getUrl()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getCaption()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getCredit()),
                new SqlParameterValue(Types.VARCHAR,
                        timeline.isHasMedia() ? null : timeline.getMedia().getThumbnailUrl()),
                new SqlParameterValue(Types.NUMERIC, timeline.getTimelineId()));
    }
}

From source file:org.apache.syncope.core.persistence.jpa.content.ContentLoaderHandler.java

private Object[] getParameters(final String tableName, final Attributes attrs) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    Map<String, Integer> colTypes = jdbcTemplate.query("SELECT * FROM " + tableName + " WHERE 0=1",
            new ResultSetExtractor<Map<String, Integer>>() {

                @Override// ww  w  . j a  v a  2  s.com
                public Map<String, Integer> extractData(final ResultSet rs) throws SQLException {
                    Map<String, Integer> colTypes = new HashMap<>();
                    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                        colTypes.put(rs.getMetaData().getColumnName(i).toUpperCase(),
                                rs.getMetaData().getColumnType(i));
                    }
                    return colTypes;
                }
            });

    Object[] parameters = new Object[attrs.getLength()];
    for (int i = 0; i < attrs.getLength(); i++) {
        Integer colType = colTypes.get(attrs.getQName(i).toUpperCase());
        if (colType == null) {
            LOG.warn("No column type found for {}", attrs.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }

        switch (colType) {
        case Types.INTEGER:
        case Types.TINYINT:
        case Types.SMALLINT:
            try {
                parameters[i] = Integer.valueOf(attrs.getValue(i));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", attrs.getValue(i));
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                parameters[i] = Long.valueOf(attrs.getValue(i));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", attrs.getValue(i));
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.DOUBLE:
            try {
                parameters[i] = Double.valueOf(attrs.getValue(i));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", attrs.getValue(i));
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.REAL:
        case Types.FLOAT:
            try {
                parameters[i] = Float.valueOf(attrs.getValue(i));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", attrs.getValue(i));
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                parameters[i] = FormatUtils.parseDate(attrs.getValue(i));
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", attrs.getValue(i));
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            parameters[i] = "1".equals(attrs.getValue(i)) ? Boolean.TRUE : Boolean.FALSE;
            break;

        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            try {
                parameters[i] = Hex.decodeHex(attrs.getValue(i).toCharArray());
            } catch (DecoderException | IllegalArgumentException e) {
                parameters[i] = attrs.getValue(i);
            }
            break;

        case Types.BLOB:
            try {
                parameters[i] = Hex.decodeHex(attrs.getValue(i).toCharArray());
            } catch (DecoderException | IllegalArgumentException e) {
                LOG.warn("Error decoding hex string to specify a blob parameter", e);
                parameters[i] = attrs.getValue(i);
            } catch (Exception e) {
                LOG.warn("Error creating a new blob parameter", e);
            }
            break;

        default:
            parameters[i] = attrs.getValue(i);
        }
    }

    return parameters;
}

From source file:org.georepublic.db.utils.ResultSetConverter.java

public static StringBuffer convertCsv(ResultSet rs) throws SQLException {

    String column_name = new String();
    StringBuffer retval = new StringBuffer();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();

    for (int h = 1; h < numColumns + 1; h++) {
        column_name = rsmd.getColumnName(h);

        if (h > 1) {
            retval.append(",");
        }/*from   ww w .  j a va2  s  . co m*/

        retval.append(column_name);
    }
    retval.append("\n");

    while (rs.next()) {

        for (int i = 1; i < numColumns + 1; i++) {
            column_name = rsmd.getColumnName(i);

            if (StringUtils.equals(column_name, "the_geom")) {
                continue;
            }
            if (StringUtils.equals(column_name, "geojson")) {
                continue;
            }
            if (i > 1) {
                retval.append(",");
            }

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                retval.append(rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                retval.append(rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                retval.append(rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                retval.append(rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                retval.append(rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                retval.append(rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                retval.append(rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                retval.append(rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                retval.append(rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                retval.append(rs.getTimestamp(column_name));
            } else {
                retval.append(rs.getObject(column_name));
            }

        }
        retval.append("\n");
    }

    return retval;
}

From source file:com.squid.core.jdbc.formatter.DefaultJDBCDataFormatter.java

public String formatJDBCObject(final Object jdbcObject, final int colType) throws SQLException {
    String value = "";

    switch (colType) {
    case Types.BIT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }//ww  w.j  a va  2  s  . c  om
        break;
    case Types.BOOLEAN:
        if (jdbcObject != null) {
            value = new Boolean(jdbcObject.toString()).toString();
        }
        break;
    case Types.BIGINT:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
    case Types.NUMERIC:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        if (jdbcObject != null) {
            value = "" + formatter.formatDecimal(jdbcObject);
        }
        break;
    case Types.CLOB:
        if (jdbcObject != null) {
            try {
                value = read((Clob) jdbcObject);
            } catch (SQLException sqle) {
                value = "";
            } catch (IOException ioe) {
                value = "";
            }
        }
        break;
    case Types.ARRAY:
        try {
            ResultSet rs = ((Array) jdbcObject).getResultSet();
            int arrayType = ((Array) jdbcObject).getBaseType();
            boolean isNotNew = false;
            while (rs.next()) {
                String current = formatJDBCObject(rs.getObject(2), arrayType);
                if ("".equals(current.trim()) == false) {
                    if (isNotNew) {
                        value = value + ",";
                    } else {
                        isNotNew = !isNotNew;
                    }
                    value = value + current;
                }
            }
            if ("".equals(value) == false) {
                value = "{" + value + "}";
            }
        } catch (SQLException sqle) {
            value = "";
        }
        break;
    case Types.JAVA_OBJECT:
        if (jdbcObject != null) {
            value = String.valueOf(jdbcObject);
        }
        break;
    case Types.DATE:
        if (jdbcObject != null) {
            value = formatter.formatDate(jdbcObject);
        }
        break;
    case Types.TIME:
        if (jdbcObject != null) {
            value = ((Time) jdbcObject).toString();
        }
        break;
    case Types.TIMESTAMP:
        if (jdbcObject != null) {
            value = formatter.formatTimestamp(jdbcObject);
        }
        break;
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        if (jdbcObject != null) {
            value = jdbcObject.toString();
        } else {
            value = "NULL";
        }
        break;
    case Types.BINARY:
        value = new String((byte[]) jdbcObject);
        break;
    default:
        value = "";
    }
    if (value == null) {
        value = "";
    }
    return value;
}

From source file:dk.netarkivet.harvester.datamodel.ScheduleDBDAO.java

/** Sets the first twelve parameters of a Schedule in the order.
 * name, comments, startdate, enddate, maxrepeats,
 * timeunit, numtimeunits, anytime, onminute, onhour,
 * ondayofweek, ondayofmonth//  ww w .j  a  v a 2 s.  c o m
 * @param s a prepared SQL statement
 * @param schedule a given schedule.
 * @throws SQLException If the operation fails.
 */
private void setScheduleParameters(PreparedStatement s, Schedule schedule) throws SQLException {
    DBUtils.setName(s, 1, schedule, Constants.MAX_NAME_SIZE);
    DBUtils.setComments(s, 2, schedule, Constants.MAX_COMMENT_SIZE);
    final Date startDate = schedule.getStartDate();
    final int fieldNum = 3;
    DBUtils.setDateMaybeNull(s, fieldNum, startDate);
    if (schedule instanceof TimedSchedule) {
        TimedSchedule ts = (TimedSchedule) schedule;
        DBUtils.setDateMaybeNull(s, 4, ts.getEndDate());
        s.setNull(5, Types.BIGINT);
    } else {
        s.setNull(4, Types.DATE);
        RepeatingSchedule rs = (RepeatingSchedule) schedule;
        s.setLong(5, rs.getRepeats());
    }
    Frequency freq = schedule.getFrequency();
    s.setInt(6, freq.ordinal());
    s.setInt(7, freq.getNumUnits());
    s.setBoolean(8, freq.isAnytime());
    DBUtils.setIntegerMaybeNull(s, 9, freq.getOnMinute());
    DBUtils.setIntegerMaybeNull(s, 10, freq.getOnHour());
    DBUtils.setIntegerMaybeNull(s, 11, freq.getOnDayOfWeek());
    DBUtils.setIntegerMaybeNull(s, 12, freq.getOnDayOfMonth());
}

From source file:co.nubetech.hiho.mapreduce.lib.db.apache.DataDrivenDBInputFormat.java

/**
 * @return the DBSplitter implementation to use to divide the table/query into InputSplits.
 *///  w ww . ja  va2 s.  c o m
protected DBSplitter getSplitter(int sqlDataType) {
    switch (sqlDataType) {
    case Types.NUMERIC:
    case Types.DECIMAL:
        return new BigDecimalSplitter();

    case Types.BIT:
    case Types.BOOLEAN:
        return new BooleanSplitter();

    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.BIGINT:
        return new IntegerSplitter();

    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
        return new FloatSplitter();

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return new TextSplitter();

    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return new DateSplitter();

    default:
        // TODO: Support BINARY, VARBINARY, LONGVARBINARY, DISTINCT, CLOB, BLOB, ARRAY
        // STRUCT, REF, DATALINK, and JAVA_OBJECT.
        return null;
    }
}

From source file:ro.nextreports.engine.querybuilder.sql.dialect.AbstractDialect.java

protected void registerDefaultJavaTypes() {
    registerJavaType(Types.BIT, Boolean.class.getName());
    registerJavaType(Types.TINYINT, Byte.class.getName());
    registerJavaType(Types.SMALLINT, Short.class.getName());
    //       registerJavaType(Types.CHAR, Character.class.getName());
    registerJavaType(Types.CHAR, String.class.getName());
    registerJavaType(Types.VARCHAR, String.class.getName());
    registerJavaType(Types.DATE, Date.class.getName());
    registerJavaType(Types.TIME, Time.class.getName());
    registerJavaType(Types.TIMESTAMP, Timestamp.class.getName());
    registerJavaType(Types.DOUBLE, Double.class.getName());
    registerJavaType(Types.FLOAT, Float.class.getName());
    registerJavaType(Types.INTEGER, Integer.class.getName());
    registerJavaType(Types.BIGINT, BigInteger.class.getName());
    //       registerJavaType(Types.BIGINT, Long.class.getName());       
    registerJavaType(Types.NUMERIC, BigDecimal.class.getName());
    registerJavaType(Types.DECIMAL, BigDecimal.class.getName());
    registerJavaType(Types.BINARY, byte[].class.getName());
    registerJavaType(Types.VARBINARY, byte[].class.getName());

    registerJavaType(Types.BLOB, String.class.getName());
    registerJavaType(Types.CLOB, String.class.getName());
    registerJavaType(Types.REAL, String.class.getName());
    registerJavaType(Types.OTHER, Object.class.getName());
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }/*from   w w w  .  ja  v a2s.com*/
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());
    boolean isKeyCol = false;

    boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, Element> keyCols = new TreeMap<String, Element>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];
            String colName = colNames[j];

            isKeyCol = (!noKey && keyField.contains(new Integer(j)));
            isNull = false;
            col = parser.createElementNS(doc, colName, NS);
            if (isKeyCol) {
                parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j));
            }
            switch (metadata.getColumnType(j)) {
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                isNull = dateVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat());
                        textVal = fF.formatDate(dateVal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                        textVal = dateFormatter.format(dateVal);
                    }
                }
            }
                break;
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                if (fF != null) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                    textVal = fF.formatNumber(numVal);
                } else {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                    textVal = numberFormatter.format(numVal);
                }
            }
                break;
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.NUMERIC:
            case Types.SMALLINT:
            case Types.TINYINT: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (isKeyCol) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyCols.put(String.valueOf(j), col);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS);
            data.appendChild(key);
            for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) {
                key.appendChild(keyColsEntry.getValue());
            }
            keyCols.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:net.sf.farrago.namespace.sfdc.SfdcUdx.java

public static void query(String query, String types, PreparedStatement resultInserter) throws SQLException {
    SoapBindingStub binding = (SoapBindingStub) FarragoUdrRuntime.getDataServerRuntimeSupport(null);

    try {//from   w ww  . jav  a2  s .c om
        QueryOptions qo = new QueryOptions();
        int batchsize = 500;
        qo.setBatchSize(new Integer(batchsize));
        binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "QueryOptions", qo);

        String objName = query;
        int fromIdx = query.lastIndexOf(" from");
        if (fromIdx > 0) {
            objName = query.substring(fromIdx + 6);
        }

        // strip off quotes for boolean values
        query = stripQuotes(query, objName);
        log.info("SFDC Query: " + query);

        QueryResult qr = binding.query(query);
        if (qr.isDone()) {
            if (qr.getRecords() != null) {
                log.info(SfdcResource.instance().RetrievedAllRecordsMsg
                        .str(Integer.toString(qr.getRecords().length), objName));
            }
        } else {
            if (qr.getRecords() != null) {
                log.info(SfdcResource.instance().RetrievingRecordsMsg
                        .str(Integer.toString(qr.getRecords().length), objName));
            }
        }
        SObject[] records = qr.getRecords();
        String[] metadataType = types.split(",");

        // query is of following format:
        // "select col1,col2,... from"
        String cols = query.substring(7);
        fromIdx = cols.lastIndexOf(" from");
        cols = cols.substring(0, fromIdx);
        cols = cols.trim();
        String[] columnValues = new String[metadataType.length];

        if (records != null) {
            boolean bContinue = true;
            while (bContinue) {
                // for each record returned in query,
                // get value of each field
                for (int i = 0; i < records.length; i++) {
                    MessageElement[] elements = records[i].get_any();
                    if (elements != null) {
                        for (int j = 0; j < elements.length; j++) {
                            MessageElement elt = elements[j];
                            String eltVal = elt.getValue();
                            columnValues[j] = (eltVal != null) ? eltVal : "null";

                            if (metadataType[j].indexOf("TIMESTAMP") != -1) {
                                // TIMESTAMP
                                if (eltVal != null) {
                                    String tstampstr = eltVal.replace("T", " ");
                                    tstampstr = tstampstr.substring(0, tstampstr.indexOf("."));
                                    java.sql.Timestamp tstamp = java.sql.Timestamp.valueOf(tstampstr);
                                    resultInserter.setTimestamp(j + 1, tstamp);
                                } else {
                                    resultInserter.setNull(j + 1, java.sql.Types.TIMESTAMP);
                                }
                            } else if (metadataType[j].indexOf("TIME") != -1) {
                                // TIME
                                if (eltVal != null) {
                                    String timestr = eltVal.substring(0, eltVal.indexOf("."));
                                    java.sql.Time time = java.sql.Time.valueOf(timestr);
                                    resultInserter.setTime(j + 1, time);
                                } else {
                                    resultInserter.setNull(j + 1, java.sql.Types.TIME);
                                }
                            } else if (metadataType[j].indexOf("DATE") != -1) {
                                // DATE
                                if (eltVal != null) {
                                    java.sql.Date dt = java.sql.Date.valueOf(eltVal);
                                    resultInserter.setDate(j + 1, dt);
                                } else {
                                    resultInserter.setNull(j + 1, java.sql.Types.DATE);
                                }
                            } else if (metadataType[j].indexOf("INTEGER") != -1) {
                                // INTEGER
                                if (eltVal != null) {
                                    int iValue = 0;
                                    iValue = Integer.parseInt(eltVal);
                                    resultInserter.setInt(j + 1, iValue);
                                } else {
                                    resultInserter.setNull(j + 1, java.sql.Types.INTEGER);
                                }
                            } else if (metadataType[j].indexOf("DOUBLE") != -1) {
                                // DOUBLE
                                if (eltVal != null) {
                                    resultInserter.setDouble(j + 1, Double.parseDouble(eltVal));
                                } else {
                                    resultInserter.setNull(j + 1, java.sql.Types.DOUBLE);
                                }
                            } else if (eltVal != null) {
                                // VARCHAR - default
                                int rightParen = metadataType[j].indexOf(")");
                                int prec = Integer.parseInt(metadataType[j].substring(8, rightParen));
                                if (eltVal.length() > prec) {
                                    eltVal = eltVal.substring(0, prec);
                                    columnValues[j] = eltVal;
                                }
                                resultInserter.setString(j + 1, eltVal);
                            } else {
                                resultInserter.setNull(j + 1, java.sql.Types.VARCHAR);
                            }
                        }
                        resultInserter.executeUpdate();
                    }
                }
                if (qr.isDone()) {
                    bContinue = false;
                } else {
                    boolean relogin = true;
                    int retryCnt = 0;
                    while (relogin) {
                        try {
                            qr = binding.queryMore(qr.getQueryLocator());
                            relogin = false;
                        } catch (AxisFault a) {
                            if (a.getFaultString().contains("Invalid Session ID") && (retryCnt < RETRY_CNT)) {
                                relogin = true;
                                retryCnt++;
                                binding = (SoapBindingStub) FarragoUdrRuntime
                                        .getDataServerRuntimeSupport(binding);
                            } else {
                                throw a;
                            }
                        }
                    }
                    records = qr.getRecords();
                    if (qr.isDone()) {
                        if (qr.getRecords() != null) {
                            log.info(SfdcResource.instance().RetrievedAllRecordsMsg
                                    .str(Integer.toString(qr.getRecords().length), objName));
                        }
                    } else {
                        if (qr.getRecords() != null) {
                            log.info(SfdcResource.instance().RetrievingRecordsMsg
                                    .str(Integer.toString(qr.getRecords().length), objName));
                        }
                    }
                }
            }
        }
    } catch (AxisFault ae) {
        SQLException retryExcn = new SQLException(ae.getFaultString(), null, 460150);
        Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn);
        throw SfdcResource.instance().BindingCallException.ex(ae.getFaultString(), chainedEx);
    } catch (RemoteException re) {
        SQLException retryExcn = new SQLException(re.getMessage(), null, 460150);
        Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn);
        throw SfdcResource.instance().BindingCallException.ex(re.getMessage(), chainedEx);
    }
}