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:org.apache.phoenix.end2end.CursorWithRowValueConstructorIT.java

@Test
/**/*  w w  w .  j  a v a  2 s  . c  o  m*/
 * Test for the precision of Date datatype when used as part of a filter within the internal Select statement.
 */
public void testCursorsWithDateDatatypeFilter() throws Exception {
    long ts = nextTimestamp();
    String tenantId = getOrganizationId();
    long currentTime = System.currentTimeMillis();
    java.sql.Date date = new java.sql.Date(currentTime);
    String strCurrentDate = date.toString();

    //Sets date to <yesterday's date> 23:59:59.999
    while (date.toString().equals(strCurrentDate)) {
        currentTime -= 1;
        date = new Date(currentTime);
    }
    //Sets date to <today's date> 00:00:00.001
    date = new Date(currentTime + 2);
    java.sql.Date midnight = new Date(currentTime + 1);

    initEntityHistoryTableValues(tenantId, getDefaultSplits(tenantId), date, ts);
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2));
    Connection conn = DriverManager.getConnection(getUrl(), props);

    String query = "select parent_id from " + ENTITY_HISTORY_TABLE_NAME
            + " WHERE (organization_id, parent_id, created_date, entity_history_id) IN ((?,?,?,?),(?,?,?,?))";

    query = query.replaceFirst("\\?", "'" + tenantId + "'");
    query = query.replaceFirst("\\?", "'" + PARENTID3 + "'");
    query = query.replaceFirst("\\?",
            "TO_DATE('" + DateUtil.getDateFormatter(DateUtil.DEFAULT_DATE_FORMAT).format(date) + "')");
    query = query.replaceFirst("\\?", "'" + ENTITYHISTID3 + "'");
    query = query.replaceFirst("\\?", "'" + tenantId + "'");
    query = query.replaceFirst("\\?", "'" + PARENTID7 + "'");
    query = query.replaceFirst("\\?",
            "TO_DATE('" + DateUtil.getDateFormatter(DateUtil.DEFAULT_DATE_FORMAT).format(date) + "')");
    query = query.replaceFirst("\\?", "'" + ENTITYHISTID7 + "'");
    String cursor = "DECLARE testCursor CURSOR FOR " + query;

    conn.prepareStatement(cursor).execute();
    cursor = "OPEN testCursor";
    conn.prepareStatement(cursor).execute();
    cursor = "FETCH NEXT FROM testCursor";

    ResultSet rs = conn.prepareStatement(cursor).executeQuery();
    assertTrue(rs.next());
    assertEquals(PARENTID3, rs.getString(1));
    rs = conn.prepareStatement(cursor).executeQuery();
    assertTrue(rs.next());
    assertEquals(PARENTID7, rs.getString(1));
    assertFalse(rs.next());

    //Test against the same table for the same records, but this time use the 'midnight' java.sql.Date instance.
    //'midnight' is identical to 'date' to the tens of millisecond precision.
    query = "select parent_id from " + ENTITY_HISTORY_TABLE_NAME
            + " WHERE (organization_id, parent_id, created_date, entity_history_id) IN ((?,?,?,?),(?,?,?,?))";
    query = query.replaceFirst("\\?", "'" + tenantId + "'");
    query = query.replaceFirst("\\?", "'" + PARENTID3 + "'");
    query = query.replaceFirst("\\?",
            "TO_DATE('" + DateUtil.getDateFormatter(DateUtil.DEFAULT_DATE_FORMAT).format(midnight) + "')");
    query = query.replaceFirst("\\?", "'" + ENTITYHISTID3 + "'");
    query = query.replaceFirst("\\?", "'" + tenantId + "'");
    query = query.replaceFirst("\\?", "'" + PARENTID7 + "'");
    query = query.replaceFirst("\\?",
            "TO_DATE('" + DateUtil.getDateFormatter(DateUtil.DEFAULT_DATE_FORMAT).format(midnight) + "')");
    query = query.replaceFirst("\\?", "'" + ENTITYHISTID7 + "'");
    cursor = "DECLARE testCursor2 CURSOR FOR " + query;

    conn.prepareStatement(cursor).execute();
    cursor = "OPEN testCursor2";
    conn.prepareStatement(cursor).execute();
    cursor = "FETCH NEXT FROM testCursor2";

    rs = conn.prepareStatement(cursor).executeQuery();
    assertTrue(!rs.next());
    String sql = "CLOSE testCursor";
    conn.prepareStatement(sql).execute();
    sql = "CLOSE testCursor2";
    conn.prepareStatement(sql).execute();
}

From source file:com.splicemachine.orc.OrcTester.java

private static Object preprocessWriteValueOld(TypeInfo typeInfo, Object value) throws IOException {
    if (value == null) {
        return null;
    }/*ww  w.j  a v a  2 s. c  o  m*/
    switch (typeInfo.getCategory()) {
    case PRIMITIVE:
        PrimitiveObjectInspector.PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo)
                .getPrimitiveCategory();
        switch (primitiveCategory) {
        case BOOLEAN:
            return value;
        case BYTE:
            return ((Number) value).byteValue();
        case SHORT:
            return ((Number) value).shortValue();
        case INT:
            return ((Number) value).intValue();
        case LONG:
            return ((Number) value).longValue();
        case FLOAT:
            return ((Number) value).floatValue();
        case DOUBLE:
            return ((Number) value).doubleValue();
        case DECIMAL:
            return HiveDecimal.create(((Decimal) value).toBigDecimal().bigDecimal());
        case STRING:
            return value;
        case CHAR:
            return new HiveChar(value.toString(), ((CharTypeInfo) typeInfo).getLength());
        case DATE:
            LocalDate localDate = LocalDate.ofEpochDay((int) value);
            ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

            long millis = zonedDateTime.toEpochSecond() * 1000;
            Date date = new Date(0);
            // mills must be set separately to avoid masking
            date.setTime(millis);
            return date;
        case TIMESTAMP:
            long millisUtc = ((Long) value).intValue();
            return new Timestamp(millisUtc);
        case BINARY:
            return ((String) value).getBytes();
        //                        return (byte[])value;
        }
        break;
    case MAP:
        MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo;
        TypeInfo keyTypeInfo = mapTypeInfo.getMapKeyTypeInfo();
        TypeInfo valueTypeInfo = mapTypeInfo.getMapValueTypeInfo();
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueOld(keyTypeInfo, entry.getKey()),
                    preprocessWriteValueOld(valueTypeInfo, entry.getValue()));
        }
        return newMap;
    case LIST:
        ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;
        TypeInfo elementTypeInfo = listTypeInfo.getListElementTypeInfo();
        List<Object> newList = new ArrayList<>(((Collection<?>) value).size());
        for (Object element : (Iterable<?>) value) {
            newList.add(preprocessWriteValueOld(elementTypeInfo, element));
        }
        return newList;
    case STRUCT:
        StructTypeInfo structTypeInfo = (StructTypeInfo) typeInfo;
        List<?> fieldValues = (List<?>) value;
        List<TypeInfo> fieldTypeInfos = structTypeInfo.getAllStructFieldTypeInfos();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueOld(fieldTypeInfos.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IOException(format("Unsupported Hive type: %s", typeInfo));
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * Add cookie to the specified client./*from w  ww . j av  a  2s  . c  o  m*/
 * 
 * @deprecated Replaced by {@link HttpClient#setCookie(String,String)}.
 * 
 * @sample
 * var cookieSet = plugins.http.setHttpClientCookie('clientName', 'JSESSIONID', 'abc', 'localhost', '/', -1, false)
 * if (cookieSet)
 * {
 *    //do something
 * }
 *
 * @param clientName 
 * @param cookieName 
 * @param cookieValue 
 * @param domain optional
 * @param path optional
 * @param maxAge optional
 * @param secure optional
 */
@Deprecated
public boolean js_setHttpClientCookie(Object[] vargs) {
    String clientName = "", cookieName = "", cookieValue = "", domain = "", path = "";
    int maxAge = -1;
    boolean secure = false;

    if (vargs.length >= 1)
        clientName = (String) vargs[0];
    if (clientName == null || "".equals(clientName.trim()))
        return false;
    DefaultHttpClient client = httpClients.get(clientName);
    if (client == null)
        return false;

    if (vargs.length >= 2)
        cookieName = (String) vargs[1];
    if (vargs.length >= 3)
        cookieValue = (String) vargs[2];
    if (vargs.length >= 4)
        domain = (String) vargs[3];
    if (vargs.length >= 5)
        path = (String) vargs[4];
    if (vargs.length >= 6) {
        maxAge = Utils.getAsInteger(vargs[5]);
        //if something is wrong, 0 is returned
        if (maxAge == 0)
            maxAge = -1;
    }
    if (vargs.length >= 7)
        secure = Utils.getAsBoolean(vargs[6]);

    if (cookieName == null || "".equals(cookieName.trim()))
        return false;
    if (cookieValue == null || "".equals(cookieValue.trim()))
        return false;

    BasicClientCookie cookie;
    cookie = new BasicClientCookie(cookieName, cookieValue);
    if (vargs.length > 3) {
        cookie.setPath(path);
        cookie.setExpiryDate(new Date(System.currentTimeMillis() + maxAge));
        cookie.setSecure(secure);
    }
    cookie.setDomain(domain);
    client.getCookieStore().addCookie(cookie);
    return true;
}

From source file:com.sfs.whichdoctor.dao.PersonDAOImpl.java

/**
 * Save the updated PersonBean./*  w w  w. j av  a2s  .c o m*/
 *
 * @param person the person
 * @param checkUser the check user
 * @param privileges the privileges
 * @param action the action
 *
 * @return the int
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
private int save(final PersonBean person, final UserBean checkUser, final PrivilegesBean privileges,
        final String action) throws WhichDoctorDaoException {

    /* Create person requires all the essential person information */
    if (person.getLastName() == null) {
        throw new WhichDoctorDaoException("Person's last name cannot be null");
    }
    if (person.getLastName().compareTo("") == 0) {
        throw new WhichDoctorDaoException("Person's last name cannot be an empty string");
    }
    if (person.getFirstName() == null) {
        throw new WhichDoctorDaoException("Person's first name cannot be null");
    }
    if (person.getFirstName().compareTo("") == 0) {
        throw new WhichDoctorDaoException("Person's first name cannot be an empty string");
    }
    if (!privileges.getPrivilege(checkUser, "people", action)) {
        throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " person");
    }

    if (person.getPersonIdentifier() == 0) {
        person.setPersonIdentifier(this.generatePersonIdentifier());
    }

    // Get the titleId and trainingStatusId values
    int titleId = 0;
    int trainingStatusId = 0;

    try {
        ObjectTypeBean object = this.getObjectTypeDAO().load("Title", person.getTitle(), person.getGender());
        titleId = object.getObjectTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading objecttype for title/gender: " + e.getMessage());
        throw new WhichDoctorDaoException("Person requires a valid title");
    }

    if (StringUtils.isBlank(person.getTrainingStatus())) {
        person.setTrainingStatus(this.defaultTrainingStatus);
    }
    try {
        ObjectTypeBean object = this.getObjectTypeDAO().load("Training Status",
                person.getTrainingStatusDetail(), person.getTrainingStatus());
        trainingStatusId = object.getObjectTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading objecttype for training status: " + e.getMessage());
        throw new WhichDoctorDaoException("Person requires a valid training status");
    }

    int personId = 0;

    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
    /* Set the Birth date */
    Date birthDate = null;
    if (person.getBirthDate() != null) {
        birthDate = new Date(person.getBirthDate().getTime());
    }
    /* Set the Deceased date */
    Date deceasedDate = null;
    if (person.getDeceasedDate() != null) {
        deceasedDate = new Date(person.getDeceasedDate().getTime());
    }

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(person.getPersonIdentifier());
    parameters.add(person.getFirstName());
    parameters.add(person.getMiddleName());
    parameters.add(person.getLastName());
    parameters.add(person.getPreferredName());
    parameters.add(person.getMaidenName());
    parameters.add(titleId);
    parameters.add(person.getHonors());
    parameters.add(birthDate);
    parameters.add(deceasedDate);
    parameters.add(trainingStatusId);
    parameters.add(person.getPassword());
    parameters.add(person.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(person.getLogMessage(action));

    /* Begin the ISB transaction */
    IsbTransactionBean isbTransaction = this.isbTransactionDAO.begin(person.getGUID());

    try {
        Integer[] result = this.performUpdate("person", person.getGUID(), parameters, "Person", checkUser,
                action);
        /* Set the returned guid and id values */
        person.setGUID(result[0]);
        personId = result[1];
    } catch (Exception e) {
        dataLogger.error("Error processing person record: " + e.getMessage());
        throw new WhichDoctorDaoException("Error processing person record: " + e.getMessage());
    }

    if (personId > 0) {

        dataLogger.info(checkUser.getDN() + " created personId: " + String.valueOf(personId));

        /* Commit the ISB transaction */
        this.isbTransactionDAO.commit(isbTransaction);

        /* Update the relevant search indexes */
        updateIndexes(person.getGUID(), action);
    }

    return personId;
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method for updating the filelist of a replicafileinfo instance.
 * Updates the following fields for the entry in the replicafileinfo:
 * <br/> filelist_status = missing.
 * <br/> filelist_checkdatetime = current time.
 *
 * The replicafileinfo is in the filelist.
 *
 * @param replicafileinfoId The id of the replicafileinfo.
 * @param con An open connection to the archive database
 *///from   ww  w .j a  v a2 s .  c  om
protected static void updateReplicaFileInfoMissingFromFilelist(long replicafileinfoId, Connection con) {
    PreparedStatement statement = null;
    try {
        // The SQL statement
        final String sql = "UPDATE replicafileinfo SET filelist_status = ?, "
                + "filelist_checkdatetime = ?, upload_status = ? " + "WHERE replicafileinfo_guid = ?";

        Date now = new Date(Calendar.getInstance().getTimeInMillis());

        // complete the SQL statement.
        statement = DBUtils.prepareStatement(con, sql, FileListStatus.MISSING.ordinal(), now,
                ReplicaStoreState.UPLOAD_FAILED.ordinal(), replicafileinfoId);

        // execute the SQL statement
        statement.executeUpdate();
        con.commit();
    } catch (Exception e) {
        String msg = "Problems updating the replicafileinfo.";
        log.warn(msg);
        throw new IOFailure(msg, e);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}

From source file:com.huison.DriverAssistant_Web.util.LoginHelper.java

public static void forgetPassword(final BaseActivity activity, final String username) {
    UmengEventSender.sendEvent(activity, UmengEventTypes.forgetPW);
    final ProgressDialog pd = new ProgressDialog(activity);
    pd.setMessage("");
    pd.show();/*from www .  j a  va  2  s  .  c  om*/
    AsyncHttpClient client = activity.getAsyncHttpClient();
    RequestParams params = new RequestParams();
    /*
     * Map<String, String> map = new HashMap<String, String>();
     * map.put("sessionkey", BaseActivity.getSESSIONKEY());
     * map.put("userid", username); map.put("mob", phone);
     * map.put("version", activity.getVersionName()); params.put("action",
     * FORGET_PASSWORD_ACTION); params.put("xml", BaseActivity.getXML(map));
     * Log.v("XML:",BaseActivity.getXML(map));
     */
    try {
        JSONObject p = new JSONObject();
        p.put("mobile", username);
        p.put("password", "wangjile");
        p.put("method", "forget");
        p.put("version", activity.getVersionName());
        p.put("devicetype", "android");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 
        String time = formatter.format(curDate);
        p.put("time", time);
        Log.v("", p.toString());
        String data = Util.DesJiaMi(p.toString(), "czxms520");
        // Log.v("",data);
        params.put("data", data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() {
        @Override
        public void onDispatchSuccess(int statusCode, Header[] headers, String result) {
            pd.dismiss();
            try {
                result = Util.decrypt(result, "czxms520");
                Log.v(TAG, "JSON" + result);
                JSONObject jo = new JSONObject(result);
                String code = jo.getString("code");
                String msg = getJSONValueAsString(jo, "message");
                if (code.equals("0")) {
                    activity.showMessageBoxAndFinish(msg);
                } else {
                    activity.showMessageBox(msg);
                }
            } catch (JSONException e) {
                activity.showMessageBox(activity.getText(R.string.server404));
                Log.e("change password error", Log.getStackTraceString(e));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable,
                BaseBinaryResponse jsonResponse) {
            pd.dismiss();
            activity.showMessageBox(activity.getText(R.string.server404));
        }

        @Override
        public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) {
        }
    });
    TimeCounter.countTime(activity, pd);
}

From source file:org.apache.phoenix.end2end.DescColumnSortOrderTest.java

private static Date date(int month, int day, int year) {
    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.MONTH, month - 1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.HOUR_OF_DAY, 10);
    cal.set(Calendar.MINUTE, 2);//from w  ww.  j av a2 s.  com
    cal.set(Calendar.SECOND, 5);
    cal.set(Calendar.MILLISECOND, 101);
    Date d = new Date(cal.getTimeInMillis());
    return d;
}

From source file:org.ednovo.gooru.controllers.v2.api.FolderRestV2Controller.java

private Collection buildCollectionFromInputParameters(final String data, final User user) {
    final Collection collection = JsonDeserializer.deserialize(data, Collection.class);
    collection.setGooruOid(UUID.randomUUID().toString());
    final ContentType contentType = getCollectionService().getContentType(ContentType.RESOURCE);
    collection.setContentType(contentType);
    collection.setCollectionType(ResourceType.Type.FOLDER.getType());
    collection.setLastModified(new Date(System.currentTimeMillis()));
    collection.setCreatedOn(new Date(System.currentTimeMillis()));
    collection.setSharing(Sharing.PRIVATE.getSharing());
    collection.setUser(user);/*from   w w w  .  jav a  2  s.c o m*/
    collection.setOrganization(user.getPrimaryOrganization());
    collection.setCreator(user);
    collection.setLastUpdatedUserUid(user.getGooruUId());

    return collection;
}

From source file:eionet.meta.service.CSVVocabularyImportServiceTest.java

/**
 * In this test, two line CSV is imported. Row 1 includes updated values for concept and DataElements (no insertion, only
 * update) Row 2 includes updated values for concept and DataElements (no insertion, only update)
 *
 * @throws Exception//  ww w  .  ja  va2 s. c  o m
 */
@Test
@Rollback
public void testIfConceptsAndElementsUpdatedAfterPurge() throws Exception {
    // get vocabulary folder
    VocabularyFolder vocabularyFolder = vocabularyService.getVocabularyFolder(TEST_VALID_VOCABULARY_ID);

    // get initial values of concepts with attributes
    List<VocabularyConcept> concepts = getVocabularyConceptsWithAttributes(vocabularyFolder);

    // get reader for CSV file
    Reader reader = getReaderFromResource("csv_import/csv_import_test_2.csv");

    // import CSV into database
    vocabularyImportService.importCsvIntoVocabulary(reader, vocabularyFolder, true, false);
    Assert.assertFalse("Transaction rolled back (unexpected)",
            transactionManager.getTransaction(null).isRollbackOnly());

    // manually update initial values of concepts for comparison
    VocabularyConcept vc8 = findVocabularyConceptById(concepts, 8);
    vc8.setDefinition("csv_test_concept_def_1_updated");
    vc8.setStatus(StandardGenericStatus.VALID);
    vc8.setAcceptedDate(new Date(System.currentTimeMillis()));
    vc8.setStatusModified(new Date(System.currentTimeMillis()));

    List<List<DataElement>> dataElements = vc8.getElementAttributes();
    List<DataElement> elems = null;
    elems = VocabularyOutputHelper.getDataElementValuesByNameAndLang("skos:prefLabel", "bg", dataElements);
    DataElement element = findDataElemByAttrValue(elems, "bg2_csv_test_concept_1");
    element.setAttributeValue("bg2_csv_test_concept_1_updated");

    elems = VocabularyOutputHelper.getDataElementValuesByNameAndLang("skos:prefLabel", "en", dataElements);
    element = findDataElemByAttrValue(elems, "en_csv_test_concept_1");
    element.setAttributeValue("en_csv_test_concept_1_updated");

    VocabularyConcept vc10 = findVocabularyConceptById(concepts, 10);
    vc10.setLabel("csv_test_concept_label_3_updated");
    vc10.setStatus(StandardGenericStatus.VALID);
    vc10.setAcceptedDate(new Date(System.currentTimeMillis()));
    vc10.setStatusModified(new Date(System.currentTimeMillis()));

    dataElements = vc10.getElementAttributes();
    elems = VocabularyOutputHelper.getDataElementValuesByNameAndLang("skos:prefLabel", "bg", dataElements);
    element = findDataElemByAttrValue(elems, "bg_csv_test_concept_3");
    element.setAttributeValue("bg_csv_test_concept_3_updated");

    elems = VocabularyOutputHelper.getDataElementValuesByNameAndLang("skos:definition", "pl", dataElements);
    element = findDataElemByAttrValue(elems, "pl_csv_test_concept_3");
    element.setAttributeValue("pl_csv_test_concept_3_updated");

    // get updated values of concepts with attributes
    List<VocabularyConcept> updatedConcepts = getVocabularyConceptsWithAttributes(vocabularyFolder);
    Assert.assertEquals("Updated Concepts does not include 2 vocabulary concepts", updatedConcepts.size(), 2);

    VocabularyConcept vc8Updated = findVocabularyConceptByIdentifier(updatedConcepts, vc8.getIdentifier());
    vc8.setId(vc8Updated.getId());
    VocabularyConcept vc10Updated = findVocabularyConceptByIdentifier(updatedConcepts, vc10.getIdentifier());
    vc10.setId(vc10Updated.getId());
    concepts = new ArrayList<VocabularyConcept>();
    concepts.add(vc8);
    concepts.add(vc10);

    // compare manually updated objects with queried ones (after import operation)
    ReflectionAssert.assertReflectionEquals(concepts, updatedConcepts, ReflectionComparatorMode.LENIENT_DATES,
            ReflectionComparatorMode.LENIENT_ORDER);
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insert(final Verblijfsobject verblijfsobject) throws DAOException {
    try {/*from ww  w  .  j a  v a 2  s  .c o m*/
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection)
                            throws SQLException {
                        PreparedStatement ps = connection.prepareStatement("insert into bag_verblijfsobject ("
                                + "bag_verblijfsobject_id," + "aanduiding_record_inactief,"
                                + "aanduiding_record_correctie," + "officieel," + "verblijfsobject_geometrie,"
                                + "oppervlakte_verblijfsobject," + "verblijfsobject_status,"
                                + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid,"
                                + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer,"
                                + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                        ps.setLong(1, verblijfsobject.getIdentificatie());
                        ps.setInt(2, verblijfsobject.getAanduidingRecordInactief().ordinal());
                        ps.setLong(3, verblijfsobject.getAanduidingRecordCorrectie());
                        ps.setInt(4, verblijfsobject.getOfficieel().ordinal());
                        ps.setString(5, verblijfsobject.getVerblijfsobjectGeometrie());
                        ps.setInt(6, verblijfsobject.getOppervlakteVerblijfsobject());
                        ps.setInt(7, verblijfsobject.getVerblijfsobjectStatus().ordinal());
                        ps.setTimestamp(8,
                                new Timestamp(verblijfsobject.getBegindatumTijdvakGeldigheid().getTime()));
                        if (verblijfsobject.getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(9, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(9,
                                    new Timestamp(verblijfsobject.getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(10, verblijfsobject.getInOnderzoek().ordinal());
                        ps.setDate(11, new Date(verblijfsobject.getDocumentdatum().getTime()));
                        ps.setString(12, verblijfsobject.getDocumentnummer());
                        ps.setLong(13, verblijfsobject.getHoofdAdres());
                        return ps;
                    }
                });
                insertGebruikersdoelen(verblijfsobject);
                insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, verblijfsobject);
                insertGerelateerdePanden(verblijfsobject);
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting verblijfsobject: " + verblijfsobject.getIdentificatie(), e);
    }
}