Example usage for java.sql Date valueOf

List of usage examples for java.sql Date valueOf

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public static Date valueOf(LocalDate date) 

Source Link

Document

Obtains an instance of Date from a LocalDate object with the same year, month and day of month value as the given LocalDate .

Usage

From source file:org.carlspring.tools.csv.dao.CSVDao.java

private void setField(PreparedStatement ps, int i, Field field, String value) throws SQLException {
    // Handle primitives
    if (field.getType().equals("int")) {
        ps.setInt(i, StringUtils.isBlank(value) ? 0 : Integer.parseInt(value));
    } else if (field.getType().equals("long")) {
        ps.setLong(i, StringUtils.isBlank(value) ? 0l : Long.parseLong(value));
    } else if (field.getType().equals("float")) {
        ps.setFloat(i, StringUtils.isBlank(value) ? 0f : Float.parseFloat(value));
    } else if (field.getType().equals("double")) {
        ps.setDouble(i, StringUtils.isBlank(value) ? 0d : Double.parseDouble(value));
    } else if (field.getType().equals("boolean")) {
        ps.setBoolean(i, StringUtils.isBlank(value) && Boolean.parseBoolean(value));
    }//  w  ww  .j av  a  2  s .  co m
    // Handle objects
    else if (field.getType().equals("java.lang.String")) {
        ps.setString(i, StringUtils.isBlank(value) ? null : value);
    } else if (field.getType().equals("java.sql.Date")) {
        ps.setDate(i, StringUtils.isBlank(value) ? null : Date.valueOf(value));
    } else if (field.getType().equals("java.sql.Timestamp")) {
        ps.setTimestamp(i, StringUtils.isBlank(value) ? null : Timestamp.valueOf(value));
    } else if (field.getType().equals("java.math.BigDecimal")) {
        ps.setBigDecimal(i, StringUtils.isBlank(value) ? null : new BigDecimal(Long.parseLong(value)));
    }
}

From source file:org.apache.ddlutils.platform.oracle.Oracle8ModelReader.java

/**
  * {@inheritDoc}/*from  w ww  .ja v  a 2 s .  co m*/
  */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException {
    Column column = super.readColumn(metaData, values);

    if (column.getDefaultValue() != null) {
        // Oracle pads the default value with spaces
        column.setDefaultValue(column.getDefaultValue().trim());
    }
    if (column.getTypeCode() == Types.DECIMAL) {
        // We're back-mapping the NUMBER columns returned by Oracle
        // Note that the JDBC driver returns DECIMAL for these NUMBER columns
        switch (column.getSizeAsInt()) {
        case 1:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.BIT);
            }
            break;
        case 3:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.TINYINT);
            }
            break;
        case 5:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.SMALLINT);
            }
            break;
        case 18:
            column.setTypeCode(Types.REAL);
            break;
        case 22:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.INTEGER);
            }
            break;
        case 38:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.BIGINT);
            } else {
                column.setTypeCode(Types.DOUBLE);
            }
            break;
        }
    } else if (column.getTypeCode() == Types.FLOAT) {
        // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to FLOAT but with
        // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
        switch (column.getSizeAsInt()) {
        case 63:
            column.setTypeCode(Types.REAL);
            break;
        case 126:
            column.setTypeCode(Types.DOUBLE);
            break;
        }
    } else if ((column.getTypeCode() == Types.DATE) || (column.getTypeCode() == Types.TIMESTAMP)) {
        // Oracle has only one DATE/TIME type, so we can't know which it is and thus map
        // it back to TIMESTAMP
        column.setTypeCode(Types.TIMESTAMP);

        // we also reverse the ISO-format adaptation, and adjust the default value to timestamp
        if (column.getDefaultValue() != null) {
            Matcher matcher = _oracleIsoTimestampPattern.matcher(column.getDefaultValue());
            Timestamp timestamp = null;

            if (matcher.matches()) {
                String timestampVal = matcher.group(1);

                timestamp = Timestamp.valueOf(timestampVal);
            } else {
                matcher = _oracleIsoDatePattern.matcher(column.getDefaultValue());
                if (matcher.matches()) {
                    String dateVal = matcher.group(1);

                    timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
                } else {
                    matcher = _oracleIsoTimePattern.matcher(column.getDefaultValue());
                    if (matcher.matches()) {
                        String timeVal = matcher.group(1);

                        timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
                    }
                }
            }
            if (timestamp != null) {
                column.setDefaultValue(timestamp.toString());
            }
        }
    } else if (TypeMap.isTextType(column.getTypeCode())) {
        column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
    }
    return column;
}

From source file:cz.fi.muni.pa165.service.layer.facade.AlbumFacadeImplementationTest.java

@Test
public void updateReleaseDate() {
    System.out.println("updateRelease");
    when(albumDao.update(backInBlackAlbum)).thenReturn(backInBlackAlbum);
    when(albumDao.findById(any(Long.class))).thenReturn(backInBlackAlbum);
    AlbumDTO result = albumFacade.updateAlbumReleaseDate(1l, Date.valueOf("1945-10-15"));
    assertEquals(mappingService.mapTo(backInBlackAlbum, AlbumDTO.class), result);
}

From source file:org.kuali.kra.committee.service.CommitteeBatchCorrespondenceServiceTest.java

/**
 * This method tests the creation of batch correspondence
 * @throws Exception/* w w w  .j  ava  2  s  .  c  om*/
 */
@Test
public void testGenerateBatchCorrespondenceForIrbNotifications() throws Exception {
    String batchCorrespondenceTypeCode = Constants.REMINDER_TO_IRB_NOTIFICATIONS;
    Committee committee = ((List<Committee>) KNSServiceLocator.getBusinessObjectService()
            .findAll(Committee.class)).get(0);
    final String committeeId = committee.getCommitteeId();
    final Date startDate = Date.valueOf("2010-06-01");
    final Date endDate = Date.valueOf("2010-06-15");

    committeeBatchCorrespondenceServiceImpl
            .setBusinessObjectService(new CommitteeTestHelper.MockBusinessObjectService());

    final ProtocolDao protocolDao = context.mock(ProtocolDao.class);
    final List<Protocol> protocols = initProtocols();
    context.checking(new Expectations() {
        {
            oneOf(protocolDao).getNotifiedProtocols(committeeId, startDate, endDate);
            will(returnValue(protocols));
        }
    });
    committeeBatchCorrespondenceServiceImpl.setProtocolDao(protocolDao);

    final ProtocolCorrespondenceTemplateService protocolCorrespondenceTemplateService = context
            .mock(ProtocolCorrespondenceTemplateService.class);
    context.checking(new Expectations() {
        {
            oneOf(protocolCorrespondenceTemplateService)
                    .getProtocolCorrespondenceTemplate(with(any(String.class)), with(any(String.class)));
            will(returnValue(new ProtocolCorrespondenceTemplate()));
        }
    });
    committeeBatchCorrespondenceServiceImpl
            .setProtocolCorrespondenceTemplateService(protocolCorrespondenceTemplateService);

    CommitteeBatchCorrespondence committeeBatchCorrespondence = (CommitteeBatchCorrespondence) committeeBatchCorrespondenceServiceImpl
            .generateBatchCorrespondence(batchCorrespondenceTypeCode, committeeId, startDate, endDate);

    // assert CommitteeBatchCorrespondence
    assertEquals(committeeId, committeeBatchCorrespondence.getCommitteeId());
    assertEquals(batchCorrespondenceTypeCode, committeeBatchCorrespondence.getBatchCorrespondenceTypeCode());
    assertEquals(startDate, committeeBatchCorrespondence.getTimeWindowStart());
    assertEquals(endDate, committeeBatchCorrespondence.getTimeWindowEnd());

    // assert CommitteeBatchCorrespondenceDetail
    assertEquals(1, committeeBatchCorrespondence.getCommitteeBatchCorrespondenceDetails().size());
    assertEquals(committeeBatchCorrespondence.getCommitteeBatchCorrespondenceId(), committeeBatchCorrespondence
            .getCommitteeBatchCorrespondenceDetails().get(0).getCommitteeBatchCorrespondenceId());
    assertEquals("Reminder to IRB Notification #1", committeeBatchCorrespondence
            .getCommitteeBatchCorrespondenceDetails().get(0).getProtocolAction().getComments());
}

From source file:org.kuali.ext.mm.ObjectUtil.java

/**
 * convert the given string into a date/*w w w . j  a v a2 s .c  om*/
 *
 * @param value the given string
 * @return a date converted from the given string
 */
public static Date formatDate(String value) {
    Date formattedDate = null;

    try {
        formattedDate = Date.valueOf(value);
    } catch (Exception e) {
        return formattedDate;
    }
    return formattedDate;
}

From source file:org.jumpmind.db.platform.mssql.MsSqlDdlReader.java

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    String defaultValue = column.getDefaultValue();

    // Sql Server tends to surround the returned default value with one or
    // two sets of parentheses
    if (defaultValue != null) {
        while (defaultValue.startsWith("(") && defaultValue.endsWith(")")) {
            defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
        }/* w  w w.jav a2 s .  c  om*/

        if (column.getMappedTypeCode() == Types.TIMESTAMP) {
            // Sql Server maintains the default values for DATE/TIME jdbc
            // types, so we have to
            // migrate the default value to TIMESTAMP
            Matcher matcher = isoDatePattern.matcher(defaultValue);
            Timestamp timestamp = null;

            if (matcher.matches()) {
                timestamp = new Timestamp(Date.valueOf(matcher.group(1)).getTime());
            } else {
                matcher = isoTimePattern.matcher(defaultValue);
                if (matcher.matches()) {
                    timestamp = new Timestamp(Time.valueOf(matcher.group(1)).getTime());
                }
            }
            if (timestamp != null) {
                defaultValue = timestamp.toString();
            }
        } else if (column.getMappedTypeCode() == Types.DECIMAL || column.getMappedTypeCode() == Types.BIGINT) {
            // For some reason, Sql Server 2005 always returns DECIMAL
            // default values with a dot
            // even if the scale is 0, so we remove the dot
            if ((column.getScale() == 0) && defaultValue.endsWith(".")) {
                defaultValue = defaultValue.substring(0, defaultValue.length() - 1);
            }
        } else if (TypeMap.isTextType(column.getMappedTypeCode())) {
            if (defaultValue.startsWith("N'") && defaultValue.endsWith("'")) {
                defaultValue = defaultValue.substring(2, defaultValue.length() - 1);
            }
            defaultValue = unescape(defaultValue, "'", "''");
        }

        column.setDefaultValue(defaultValue);
    }

    if ((column.getMappedTypeCode() == Types.DECIMAL) && (column.getSizeAsInt() == 19)
            && (column.getScale() == 0)) {
        column.setMappedTypeCode(Types.BIGINT);
    }

    // These columns return sizes and/or decimal places with the metat data from MSSql Server however
    // the values are not adjustable through the create table so they are omitted 
    if (column.getJdbcTypeName() != null && (column.getJdbcTypeName().equals("smallmoney")
            || column.getJdbcTypeName().equals("money") || column.getJdbcTypeName().equals("timestamp")
            || column.getJdbcTypeName().equals("uniqueidentifier") || column.getJdbcTypeName().equals("time")
            || column.getJdbcTypeName().equals("datetime2") || column.getJdbcTypeName().equals("date"))) {
        removePlatformSizeAndDecimal(column);
    }
    return column;
}

From source file:com.lyft.hive.serde.DynamoDbSerDe.java

@Override
public Object deserialize(Writable blob) throws SerDeException {
    ArrayList<Object> row = buildRow();
    Text rowText = (Text) blob;
    Map<String, String> values = decomposeRow(rowText.toString());

    for (int c = 0; c < numColumns; c++) {
        try {//from   w  ww  .j  ava 2  s.  c o m
            String t = values.get(columnNames.get(c));
            TypeInfo typeInfo = columnTypes.get(c);

            // Convert the column to the correct type when needed and set in row obj
            PrimitiveTypeInfo pti = (PrimitiveTypeInfo) typeInfo;
            switch (pti.getPrimitiveCategory()) {
            case STRING:
                row.set(c, t);
                break;
            case BYTE:
                Byte b;
                b = Byte.valueOf(t);
                row.set(c, b);
                break;
            case SHORT:
                Short s;
                s = Short.valueOf(t);
                row.set(c, s);
                break;
            case INT:
                Integer i;
                i = Integer.valueOf(t);
                row.set(c, i);
                break;
            case LONG:
                Long l;
                l = Long.valueOf(t);
                row.set(c, l);
                break;
            case FLOAT:
                Float f;
                f = Float.valueOf(t);
                row.set(c, f);
                break;
            case DOUBLE:
                Double d;
                d = Double.valueOf(t);
                row.set(c, d);
                break;
            case BOOLEAN:
                Boolean bool;
                bool = Boolean.valueOf(t);
                row.set(c, bool);
                break;
            case TIMESTAMP:
                row.set(c, parseTimestamp(t));
                break;
            case DATE:
                Date date;
                date = Date.valueOf(t);
                row.set(c, date);
                break;
            case DECIMAL:
                HiveDecimal bd = HiveDecimal.create(t);
                row.set(c, bd);
                break;
            case CHAR:
                HiveChar hc = new HiveChar(t, ((CharTypeInfo) typeInfo).getLength());
                row.set(c, hc);
                break;
            case VARCHAR:
                HiveVarchar hv = new HiveVarchar(t, ((VarcharTypeInfo) typeInfo).getLength());
                row.set(c, hv);
                break;
            default:
                throw new SerDeException("Unsupported type " + typeInfo);
            }
        } catch (RuntimeException e) {
            row.set(c, null);
        }
    }
    return row;
}

From source file:org.geoserver.wms.dimension.RasterTimeDimensionDefaultValueTest.java

@Test
public void testExplicitNearestToGivenTimeCoverageSelector() throws Exception {
    String preferredTimeStr = "2009-01-01T00:00:00.000Z";
    // Use explicit default value strategy: 
    DimensionDefaultValueSetting defaultValueSetting = new DimensionDefaultValueSetting();
    defaultValueSetting.setStrategyType(Strategy.NEAREST);
    defaultValueSetting.setReferenceValue(preferredTimeStr);
    setupCoverageTimeDimension(WATTEMP_FUTURE, defaultValueSetting);

    //From src/test/resources/org/geoserver/wms/watertemp.zip:
    Date expected = Date.valueOf("2008-11-01");

    CoverageInfo coverage = getCatalog().getCoverageByName(WATTEMP_FUTURE.getLocalPart());

    java.util.Date d = wms.getDefaultTime(coverage);
    assertTrue("Returns a valid Default time", d != null);
    assertTrue("Default time should be the closest one", d.getTime() == expected.getTime());
}

From source file:org.jumpmind.db.platform.oracle.OracleDdlReader.java

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    if (column.getMappedTypeCode() == Types.DECIMAL) {
        // We're back-mapping the NUMBER columns returned by Oracle
        // Note that the JDBC driver returns DECIMAL for these NUMBER
        // columns
        if (column.getScale() <= -127 || column.getScale() >= 127) {
            if (column.getSizeAsInt() == 0) {
                /*//from w  ww.  ja v  a2  s  .c o  m
                 * Latest oracle jdbc drivers for 11g return (0,-127) for
                 * types defined as integer resulting in bad mappings.
                 * NUMBER without scale or precision looks the same as
                 * INTEGER in the jdbc driver. We must check the Oracle
                 * meta data to see if type is an INTEGER.
                 */
                if (isColumnInteger((String) values.get("TABLE_NAME"), (String) values.get("COLUMN_NAME"))) {
                    column.setMappedTypeCode(Types.BIGINT);
                }
            } else if (column.getSizeAsInt() <= 63) {
                column.setMappedTypeCode(Types.REAL);
            } else {
                column.setMappedTypeCode(Types.DOUBLE);
            }
        }
    } else if (column.getMappedTypeCode() == Types.FLOAT) {
        // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to
        // FLOAT but with
        // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
        switch (column.getSizeAsInt()) {
        case 63:
            column.setMappedTypeCode(Types.REAL);
            break;
        case 126:
            column.setMappedTypeCode(Types.DOUBLE);
            break;
        }
    } else if ((column.getMappedTypeCode() == Types.DATE) || (column.getMappedTypeCode() == Types.TIMESTAMP)) {
        // we also reverse the ISO-format adaptation, and adjust the default
        // value to timestamp
        if (column.getDefaultValue() != null) {
            Timestamp timestamp = null;

            Matcher matcher = oracleIsoTimestampPattern.matcher(column.getDefaultValue());

            if (matcher.matches()) {
                String timestampVal = matcher.group(1);
                timestamp = Timestamp.valueOf(timestampVal);
            } else {
                matcher = oracleIsoDatePattern.matcher(column.getDefaultValue());
                if (matcher.matches()) {
                    String dateVal = matcher.group(1);
                    timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
                } else {
                    matcher = oracleIsoTimePattern.matcher(column.getDefaultValue());
                    if (matcher.matches()) {
                        String timeVal = matcher.group(1);

                        timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
                    }
                }
            }
            if (timestamp != null) {
                column.setDefaultValue(timestamp.toString());
            }
        }
    } else if (TypeMap.isTextType(column.getMappedTypeCode())) {
        String defaultValue = column.getDefaultValue();
        if (isNotBlank(defaultValue) && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
            defaultValue = defaultValue.substring(2, defaultValue.length() - 2);
        }
        column.setDefaultValue(unescape(defaultValue, "'", "''"));
    }
    return column;
}