Example usage for java.sql Date Date

List of usage examples for java.sql Date Date

Introduction

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

Prototype

public Date(long date) 

Source Link

Document

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Usage

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

/**
 * Tests the method buildDataTableRows./*from ww w. j av a2  s  .com*/
 *
 * @throws SQLException Thrown when the connection to the database failed.
 */
public void testBuildDataTableRows() throws SQLException {
    // Build Timestamp, Date ant Time objects for the date February 8, 2008
    // 09:01:10. Set their values in the table.
    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    gc.set(2008, 1, 8, 9, 1, 10);
    // Set the milliseconds explicitly, otherwise the milliseconds from the
    // time the gc was initialized are used.
    gc.set(GregorianCalendar.MILLISECOND, 0);

    Date date = new Date(gc.getTimeInMillis());
    Time time = new Time(gc.get(GregorianCalendar.HOUR), gc.get(GregorianCalendar.MINUTE),
            gc.get(GregorianCalendar.SECOND));
    Timestamp timestamp = new Timestamp(gc.get(GregorianCalendar.YEAR) - 1900, gc.get(GregorianCalendar.MONTH),
            gc.get(GregorianCalendar.DAY_OF_MONTH), gc.get(GregorianCalendar.HOUR),
            gc.get(GregorianCalendar.MINUTE), gc.get(GregorianCalendar.SECOND), 0);

    // Create the table rows.
    List<Object> row1 = Lists.<Object>newArrayList(100, "Yaron", null, 'M', 1000, false, date, timestamp, time);
    List<Object> row2 = Lists.<Object>newArrayList(200, "Moran", "Bar", 'F', 2000, null, null, null, null);
    List<Object> row3 = Lists.<Object>newArrayList(300, "Shir", "Gal", 'F', null, true, null, null, null);
    rows.add(row1);
    rows.add(row2);
    rows.add(row3);

    // Get the mock result set for the table.
    ResultSet rs = new MockResultSet(rows, NUM_OF_COLS, labels, types);

    List<String> columnIdsList = Lists.newArrayList("id", "fname", "lname", "gender", "salary", "ismarried",
            "startdate", "timestamp", "time");

    // Get the table description using the mock result set.
    DataTable dataTable = SqlDataSourceHelper.buildColumns(rs, columnIdsList);
    assertNotNull(dataTable);

    // Make sure the number of columns in the table description is correct.
    assertEquals(NUM_OF_COLS, dataTable.getNumberOfColumns());

    // Get the columns description list.
    List<ColumnDescription> columnsDescriptionList = dataTable.getColumnDescriptions();

    // Make sure the type of each column is correct.
    assertEquals(ValueType.NUMBER, columnsDescriptionList.get(0).getType());
    assertEquals(ValueType.TEXT, columnsDescriptionList.get(1).getType());
    assertEquals(ValueType.TEXT, columnsDescriptionList.get(2).getType());
    assertEquals(ValueType.TEXT, columnsDescriptionList.get(3).getType());
    assertEquals(ValueType.NUMBER, columnsDescriptionList.get(4).getType());
    assertEquals(ValueType.BOOLEAN, columnsDescriptionList.get(5).getType());
    assertEquals(ValueType.DATE, columnsDescriptionList.get(6).getType());
    assertEquals(ValueType.DATETIME, columnsDescriptionList.get(7).getType());
    assertEquals(ValueType.TIMEOFDAY, columnsDescriptionList.get(8).getType());

    // Make sure the label of each column is correct.
    assertEquals("ID", columnsDescriptionList.get(0).getLabel());
    assertEquals("Fname", columnsDescriptionList.get(1).getLabel());
    assertEquals("Lname", columnsDescriptionList.get(2).getLabel());
    assertEquals("Gender", columnsDescriptionList.get(3).getLabel());
    assertEquals("Salary", columnsDescriptionList.get(4).getLabel());
    assertEquals("IsMarried", columnsDescriptionList.get(5).getLabel());
    assertEquals("StartDate", columnsDescriptionList.get(6).getLabel());
    assertEquals("TimeStamp", columnsDescriptionList.get(7).getLabel());
    assertEquals("Time", columnsDescriptionList.get(8).getLabel());

    // Build the table rows.
    SqlDataSourceHelper.buildRows(dataTable, rs);

    assertNotNull(dataTable);

    // Make sure the number of rows int the table is correct.
    assertEquals(3, dataTable.getNumberOfRows());

    // Make sure the type of the data table cells is correct.
    for (int i = 0; i < dataTable.getNumberOfRows(); i++) {
        assertEquals(ValueType.NUMBER, dataTable.getRow(i).getCell(0).getValue().getType());
        assertEquals(ValueType.TEXT, dataTable.getRow(i).getCell(1).getValue().getType());
        assertEquals(ValueType.TEXT, dataTable.getRow(i).getCell(2).getValue().getType());
        assertEquals(ValueType.TEXT, dataTable.getRow(i).getCell(3).getValue().getType());
        assertEquals(ValueType.NUMBER, dataTable.getRow(i).getCell(4).getValue().getType());
        assertEquals(ValueType.BOOLEAN, dataTable.getRow(i).getCell(5).getValue().getType());
        assertEquals(ValueType.DATE, dataTable.getRow(i).getCell(6).getValue().getType());
        assertEquals(ValueType.DATETIME, dataTable.getRow(i).getCell(7).getValue().getType());
        assertEquals(ValueType.TIMEOFDAY, dataTable.getRow(i).getCell(8).getValue().getType());
    }

    // Make sure the value of the data table cells is correct. For cells with
    // null value, check that the value equals to the null value format of the
    // specific type value.
    assertEquals(new NumberValue(100.0), dataTable.getRow(0).getCell(0).getValue());
    assertEquals("Yaron", dataTable.getRow(0).getCell(1).getValue().toString());
    assertEquals(new TextValue(""), dataTable.getRow(0).getCell(2).getValue());
    assertEquals("Bar", dataTable.getRow(1).getCell(2).getValue().toString());
    assertEquals("F", dataTable.getRow(1).getCell(3).getValue().toString());
    assertEquals(BooleanValue.getNullValue(), dataTable.getRow(1).getCell(5).getValue());
    assertEquals(NumberValue.getNullValue(), dataTable.getRow(2).getCell(4).getValue());
    assertEquals("true", dataTable.getRow(2).getCell(5).getValue().toString());
    assertEquals(dataTable.getRow(0).getCell(6).getValue().toString(), new DateValue(gc),
            dataTable.getRow(0).getCell(6).getValue());
    assertEquals(new DateTimeValue(gc), dataTable.getRow(0).getCell(7).getValue());
    assertEquals(new TimeOfDayValue(gc), dataTable.getRow(0).getCell(8).getValue());
    assertEquals(DateValue.getNullValue(), dataTable.getRow(1).getCell(6).getValue());
    assertEquals(DateTimeValue.getNullValue(), dataTable.getRow(2).getCell(7).getValue());
    assertEquals(TimeOfDayValue.getNullValue(), dataTable.getRow(2).getCell(8).getValue());
}

From source file:org.apache.phoenix.jdbc.PhoenixResultSet.java

@Override
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
    checkCursorState();//from   www .ja  va  2  s.  c  o  m
    Date value = (Date) rowProjector.getColumnProjector(columnIndex - 1).getValue(currentRow, PDate.INSTANCE,
            ptr);
    cal.setTime(value);
    return new Date(cal.getTimeInMillis());
}

From source file:gobblin.converter.jdbc.AvroToJdbcEntryConverter.java

@Override
public Iterable<JdbcEntryData> convertRecord(JdbcEntrySchema outputSchema, GenericRecord record,
        WorkUnitState workUnit) throws DataConversionException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Converting " + record);
    }/*  ww  w . j  a  v  a 2s  .co m*/
    List<JdbcEntryDatum> jdbcEntryData = Lists.newArrayList();
    for (JdbcEntryMetaDatum entry : outputSchema) {
        final String colName = entry.getColumnName();
        final JdbcType jdbcType = entry.getJdbcType();
        final Object val = record.get(tryConvertColumn(colName, this.jdbcToAvroColPairs));

        if (val == null) {
            jdbcEntryData.add(new JdbcEntryDatum(colName, null));
            continue;
        }

        if (!JDBC_SUPPORTED_TYPES.contains(jdbcType)) {
            throw new DataConversionException("Unsupported JDBC type detected " + jdbcType);
        }

        switch (jdbcType) {
        case VARCHAR:
            jdbcEntryData.add(new JdbcEntryDatum(colName, val.toString()));
            continue;
        case INTEGER:
        case BOOLEAN:
        case BIGINT:
        case FLOAT:
        case DOUBLE:
            jdbcEntryData.add(new JdbcEntryDatum(colName, val));
            continue;
        //        case BOOLEAN:
        //          jdbcEntryData.add(new JdbcEntryDatum(colName, Boolean.valueOf((boolean) val)));
        //          continue;
        //        case BIGINT:
        //          jdbcEntryData.add(new JdbcEntryDatum(colName, Long.valueOf((long) val)));
        //          continue;
        //        case FLOAT:
        //          jdbcEntryData.add(new JdbcEntryDatum(colName, Float.valueOf((float) val)));
        //          continue;
        //        case DOUBLE:
        //          jdbcEntryData.add(new JdbcEntryDatum(colName, Double.valueOf((double) val)));
        //          continue;
        case DATE:
            jdbcEntryData.add(new JdbcEntryDatum(colName, new Date((long) val)));
            continue;
        case TIME:
            jdbcEntryData.add(new JdbcEntryDatum(colName, new Time((long) val)));
            continue;
        case TIMESTAMP:
            jdbcEntryData.add(new JdbcEntryDatum(colName, new Timestamp((long) val)));
            continue;
        default:
            throw new DataConversionException(jdbcType + " is not supported");
        }
    }
    JdbcEntryData converted = new JdbcEntryData(jdbcEntryData);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Converted data into " + converted);
    }
    return new SingleRecordIterable<>(converted);
}

From source file:org.everit.jira.hr.admin.SchemeUsersComponent.java

private QueryResultWithCount<SchemeUserDTO> querySchemeUsers(final int pageIndex, final long schemeId,
        final String userName, final boolean currentTimeRanges) {
    return querydslSupport.execute((connection, configuration) -> {
        QDateRange qDateRange = QDateRange.dateRange;
        QCwdUser qCwdUser = QCwdUser.cwdUser;

        SQLQuery<SchemeUserDTO> query = new SQLQuery<>(connection, configuration);
        query.from(qUserSchemeEntityParameter.userSchemeEntityPath).innerJoin(qDateRange)
                .on(qDateRange.dateRangeId.eq(qUserSchemeEntityParameter.dateRangeId)).innerJoin(qCwdUser)
                .on(qCwdUser.id.eq(qUserSchemeEntityParameter.userId));

        QAvatar qAvatar = AvatarUtil.joinAvatarToCwdUser(query, qCwdUser, "avatar");

        List<Predicate> predicates = new ArrayList<>();
        predicates.add(qUserSchemeEntityParameter.userSchemeSchemeId.eq(schemeId));

        if (currentTimeRanges) {
            Date currentDate = new Date(new java.util.Date().getTime());
            predicates//from w w w. ja  v  a  2 s.  co  m
                    .add(qDateRange.startDate.loe(currentDate).and(qDateRange.endDateExcluded.gt(currentDate)));
        }

        if (userName != null) {
            predicates.add(qCwdUser.userName.eq(userName));
        }

        Expression<Long> defaultAvatarId = ConstantImpl.create(AvatarUtil.DEFAULT_AVATAR_ID);

        StringExpression userDisplayNameExpression = qCwdUser.displayName.as("userDisplayName");
        query.select(Projections.fields(SchemeUserDTO.class,
                qUserSchemeEntityParameter.userSchemeId.as("userSchemeId"), qDateRange.dateRangeId,
                qCwdUser.userName, userDisplayNameExpression, qDateRange.startDate, qDateRange.endDateExcluded,
                new Coalesce<>(Long.class, qAvatar.id, defaultAvatarId).as("avatarId"),
                qAvatar.owner.as("avatarOwner")));

        query.where(predicates.toArray(new Predicate[0]));

        long count = query.fetchCount();

        query.orderBy(userDisplayNameExpression.asc(), qDateRange.startDate.desc());
        long offset = PAGE_SIZE * (pageIndex - 1);
        if (offset >= count) {
            offset = PAGE_SIZE * (count / PAGE_SIZE - 1);
            if (offset < 0) {
                offset = 0;
            }
        }

        List<SchemeUserDTO> resultSet;
        if (offset >= count) {
            resultSet = Collections.emptyList();
        } else {
            resultSet = query.limit(PAGE_SIZE).offset(offset).fetch();
        }

        QueryResultWithCount<SchemeUserDTO> result = new QueryResultWithCount<>(resultSet, count);
        return result;
    });
}

From source file:de.tuttas.restful.AnwesenheitsManager.java

/**
 * Liste der Anwesenheit einer Klasse ber einen Bereich Adresse
 * /api/v1/anwesenheit/{Name der Klasse}/{von Datum}/{bis Datum}
 *
 * @param kl Name der Klasse//from   w  w w . ja va  2  s.c o m
 * @param from Startdatum (inclusiv)
 * @param to EndDatum (inclusiv)
 * @return Liste der Anwesenheitsobjekte
 */
@GET
@Path("/{klasse}/{from}/{to}")
public List<AnwesenheitObjekt> getAnwesenheit(@PathParam("klasse") String kl, @PathParam("from") Date from,
        @PathParam("to") Date to) {
    to = new Date(to.getTime() + 24 * 60 * 60 * 1000);
    Log.d("Webservice Anwesenheit GET from=" + from + " to=" + to);
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl);
    query.setParameter("paramFromDate", from);
    query.setParameter("paramToDate", to);

    List<AnwesenheitEintrag> anwesenheit = query.getResultList();

    Query qb = em.createNamedQuery("findBemerkungbyDate");
    qb.setParameter("paramFromDate", from);
    qb.setParameter("paramToDate", to);

    List<String> ids = new ArrayList<>();
    for (AnwesenheitEintrag ae : anwesenheit) {
        ids.add("" + ae.getID_SCHUELER());
    }
    List<Bemerkung> bemerkungen = null;
    qb.setParameter("idList", ids);
    if (ids.size() > 0) {
        bemerkungen = qb.getResultList();
        Log.d("Result List Bemerkunken:" + bemerkungen);
    }
    return getData(anwesenheit, bemerkungen);
}

From source file:io.heming.accountbook.ui.MainFrame.java

private void showAddRecordDialog() {
    if (categories.isEmpty()) {
        JOptionPane.showMessageDialog(this, "???????",
                "", JOptionPane.ERROR_MESSAGE);
        return;//  www . j a  v a 2s  .c om
    }
    System.out.println("add record");
    try {
        Record record = new Record();
        record.setCategory(categories.get(0));
        record.setPrice(48.0);
        record.setDate(new Date(Calendar.getInstance().getTimeInMillis()));
        RecordDialog dialog = new RecordDialog(record, this, false);
        dialog.setSize(400, 250);
        dialog.setLocationRelativeTo(this);
        dialog.setIconImage(new ImageIcon(getClass().getResource("edit-add-3.png")).getImage());
        dialog.setVisible(true);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }
}

From source file:com.eyeq.pivot4j.impl.PivotModelImpl.java

/**
 * @param connection/*from ww  w  . j  a va  2s .c  o  m*/
 * @param mdx
 * @return
 * @throws OlapException
 */
protected CellSet executeMdx(OlapConnection connection, String mdx) throws OlapException {
    if (logger.isDebugEnabled()) {
        logger.debug(mdx);
    }

    Date start = new Date(System.currentTimeMillis());

    OlapStatement stmt = connection.createStatement();
    CellSet result = stmt.executeOlapQuery(mdx);

    long duration = System.currentTimeMillis() - start.getTime();
    if (logger.isInfoEnabled()) {
        logger.info(String.format("Query execution time : %d ms", duration));
    }

    fireQueryExecuted(start, duration, mdx);

    return result;
}

From source file:de.powerstaff.business.service.impl.ProfileSearchServiceImpl.java

@Override
public synchronized List<FreelancerProfile> loadProfilesFor(Freelancer aFreelancer) {
    List<FreelancerProfile> theProfiles = new ArrayList<FreelancerProfile>();

    if (aFreelancer != null && aFreelancer.getCode() != null) {

        String theCode = aFreelancer.getCode().trim().toLowerCase();
        Set<File> theFilesForCode = fileSystemCache.getFilesForCode(theCode);

        if (theFilesForCode != null) {

            String theClientBaseDir = systemParameterService.getIndexerNetworkDir();
            if (!theClientBaseDir.endsWith("\\")) {
                theClientBaseDir += "\\";
            }/*from  w  ww .  j  a v  a2s  .com*/
            String theServerBaseDir = systemParameterService.getIndexerSourcePath();
            if (!theServerBaseDir.endsWith("\\")) {
                theServerBaseDir += "\\";
            }

            SimpleDateFormat theFormat = new SimpleDateFormat("dd.MM.yyyy");

            for (File theFile : theFilesForCode) {
                FreelancerProfile theProfile = new FreelancerProfile();
                theProfile.setName(theFile.getName());
                theProfile.setInfotext("Aktualisiert : " + theFormat.format(new Date(theFile.lastModified())));
                theProfile.setFileOnserver(theFile);

                String theStrippedPath = theFile.toString().substring(theServerBaseDir.length());
                theProfile.setFileName(theClientBaseDir + theStrippedPath);

                theProfiles.add(theProfile);
            }
        }

    }
    return theProfiles;
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column/*from  ww  w  .  j av a2s .c o  m*/
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateBugGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-bug-service" + sAccountId);
        try {/*from   w ww  .  jav  a 2s  .c om*/
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_tracker_bug` SET " + "summary = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignuser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.BUG.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5,
                                    MoreObjects.firstNonNull(ganttItem.getProgress(), 0d));
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setInt(9, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-bug-service" + sAccountId);
            lock.unlock();
        }
    }
}