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.teiid.resource.adapter.google.dataprotocol.GoogleDataProtocolAPI.java

static Object convertValue(Calendar cal, Object object, SpreadsheetColumnType type) {
    switch (type) {
    case DATE:// w  w w. j  a v  a 2s.  c  om
    case DATETIME:
        if (object instanceof String) {
            String stringVal = (String) object;
            if (stringVal.startsWith("Date(") && stringVal.endsWith(")")) { //$NON-NLS-1$ //$NON-NLS-2$
                String[] parts = stringVal.substring(5, stringVal.length() - 1).split(","); //$NON-NLS-1$
                if (cal == null) {
                    cal = Calendar.getInstance();
                }
                cal.clear();
                if (type == SpreadsheetColumnType.DATETIME) {
                    cal.set(Integer.valueOf(parts[0]), Integer.valueOf(parts[1]), Integer.valueOf(parts[2]),
                            Integer.valueOf(parts[3]), Integer.valueOf(parts[4]), Integer.valueOf(parts[5]));
                    object = new Timestamp(cal.getTimeInMillis());
                } else {
                    cal.set(Integer.valueOf(parts[0]), Integer.valueOf(parts[1]), Integer.valueOf(parts[2]));
                    object = new Date(cal.getTimeInMillis());
                }
            }
        }
        break;
    case TIMEOFDAY:
        if (object instanceof List<?>) {
            List<Double> doubleVals = (List<Double>) object;
            if (cal == null) {
                cal = Calendar.getInstance();
            }
            cal.clear();
            cal.set(Calendar.YEAR, 1970);
            cal.set(Calendar.MONTH, Calendar.JANUARY);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.HOUR, doubleVals.get(0).intValue());
            cal.set(Calendar.MINUTE, doubleVals.get(1).intValue());
            cal.set(Calendar.SECOND, doubleVals.get(2).intValue());
            //TODO: it's not proper to convey the millis on a time value
            cal.set(Calendar.MILLISECOND, doubleVals.get(3).intValue());
            object = new Time(cal.getTimeInMillis());
        }
        break;
    }
    return object;
}

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

/**
 * Save.//from  ww  w.j av a2 s.c  om
 *
 * @param reimbursement the reimbursement
 * @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 ReimbursementBean reimbursement, final UserBean checkUser,
        final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException {

    /* Create reimbursement requires all the essential information */
    if (reimbursement.getDescription() == null) {
        throw new WhichDoctorDaoException("Reimbursement description field " + "cannot be null");
    }
    if (reimbursement.getDescription().compareTo("") == 0) {
        throw new WhichDoctorDaoException("Reimbursement description field " + "cannot be an empty string");
    }
    if (reimbursement.getPersonId() == 0 && reimbursement.getOrganisationId() == 0) {
        throw new WhichDoctorDaoException("Reimbursement must be " + "attributed to a person or organisation");
    }
    if (!privileges.getPrivilege(checkUser, "reimbursements", action)) {
        throw new WhichDoctorDaoException("Insufficient user credentials " + "to " + action + " reimbursement");
    }

    /* Find Reimbursement Type Id */
    int typeId = 0;
    try {
        FinancialTypeBean financialObject = this.financialTypeDAO.load("Reimbursement",
                reimbursement.getTypeName(), reimbursement.getClassName());
        typeId = financialObject.getFinancialTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading financial type for reimbursement: " + e.getMessage());
        throw new WhichDoctorDaoException("Reimbursement requires a type");
    }

    /* Check if the reimbursement number exists, if not create one */
    reimbursement
            .setNumber(this.checkNumber("reimbursement", reimbursement.getNumber(), reimbursement.getIssued()));

    int reimbursementId = 0;

    Date issued = new Date(Calendar.getInstance().getTimeInMillis());
    Date meetingDate = null;
    if (reimbursement.getIssued() != null) {
        issued = new Date(reimbursement.getIssued().getTime());
    }
    if (reimbursement.getMeetingDate() != null) {
        meetingDate = new Date(reimbursement.getMeetingDate().getTime());
    }
    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(reimbursement.getDescription());
    parameters.add(reimbursement.getLocation());
    parameters.add(meetingDate);
    parameters.add(reimbursement.getNumber());
    parameters.add(reimbursement.getCancelled());
    parameters.add(reimbursement.getPersonId());
    parameters.add(reimbursement.getOrganisationId());
    parameters.add(issued);
    parameters.add(typeId);
    parameters.add(reimbursement.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(reimbursement.getLogMessage(action));

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

    if (reimbursementId > 0) {
        dataLogger.info(checkUser.getDN() + " created reimbursementId: " + String.valueOf(reimbursementId));
    }

    return reimbursementId;
}

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

/**
 * Save./* w  ww  .  j a va  2s .c o  m*/
 *
 * @param item the item
 * @param checkUser the check user
 * @param privileges the privileges
 * @param action the action
 * @param isbMapping the ISB mapping of the parent group - if null then none at all
 *
 * @return the int
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
private int save(final ItemBean item, final UserBean checkUser, final PrivilegesBean privileges,
        final String action, final String isbMapping) throws WhichDoctorDaoException {

    /* Check required information within item bean is present */
    if (item.getObject1GUID() == 0) {
        throw new WhichDoctorDaoException("Item requires a valid Object1GUID");
    }
    if (item.getObject2GUID() == 0) {
        throw new WhichDoctorDaoException("Item requires a valid Object2GUID");
    }
    if (item.getPermission() == null) {
        throw new WhichDoctorDaoException("The item's permission cannot be null");
    }
    if (StringUtils.isBlank(item.getPermission())) {
        throw new WhichDoctorDaoException("The item's permssion cannot be set to nothing");
    }
    if (!privileges.getPrivilege(checkUser, item.getPermission(), action)) {
        throw new WhichDoctorDaoException(
                "Insufficient user credentials to " + action + " item (" + item.getPermission() + ")");
    }

    int itemTypeId = 0;
    try {
        String dbItemType = item.getItemType();
        if (StringUtils.equalsIgnoreCase(item.getItemType(), "Employee")
                || StringUtils.equalsIgnoreCase(item.getItemType(), "Employer")) {
            dbItemType = "Employment";
        }
        ObjectTypeBean object = this.getObjectTypeDAO().load("Item Type", "", dbItemType);
        itemTypeId = object.getObjectTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading objecttype for item type: " + e.getMessage());
        throw new WhichDoctorDaoException("Item requires a valid type");
    }

    int itemId = 0;

    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
    Date startDate = null;
    Date endDate = null;
    if (item.getStartDate() != null) {
        startDate = new Date(item.getStartDate().getTime());
    }
    if (item.getEndDate() != null) {
        endDate = new Date(item.getEndDate().getTime());
    }

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(item.getObject1GUID());
    parameters.add(item.getObject2GUID());
    parameters.add(item.getReferenceGUID());
    parameters.add(item.getTitle());
    parameters.add(item.getComment());
    parameters.add(item.getWeighting());
    parameters.add(startDate);
    parameters.add(endDate);
    parameters.add(itemTypeId);
    parameters.add(item.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(item.getLogMessage(action));

    IsbTransactionBean isbTransaction = null;
    if (isbMapping != null) {
        /* The item has an ISB mapping - begin the ISB transaction */
        isbTransaction = this.isbTransactionDAO.begin(item.getObject2GUID());
    }

    String sqlType = "item";
    if (StringUtils.equalsIgnoreCase(item.getItemType(), "Candidate")) {
        sqlType = "candidate";
    }
    if (StringUtils.equalsIgnoreCase(item.getItemType(), "Vote")) {
        sqlType = "vote";
    }
    try {
        Integer[] result = this.performUpdate(sqlType, item.getGUID(), parameters, "Item", checkUser, action);
        /* Set the returned guid and id values */
        item.setGUID(result[0]);
        itemId = result[1];
    } catch (Exception e) {
        dataLogger.error("Error processing item record: " + e.getMessage());
        throw new WhichDoctorDaoException("Error processing item record: " + e.getMessage());
    }

    if (itemId > 0) {
        /* Update the indexes */
        updateIndexes(item.getObject2GUID(), item.getItemType());

        if (isbTransaction != null) {
            // Commit the transaction to the ISB
            this.isbTransactionDAO.commit(isbTransaction);
        }
    }

    return itemId;
}

From source file:ips1ap101.lib.base.util.TimeUtils.java

public static java.util.Date parse(String pdq) {
    String string = pdq == null ? null : pdq.toString().trim();
    if (string == null || string.isEmpty()) {
        return null;
    }/*from   w  w  w .  jav a 2  s  .  com*/
    int year = 1970;
    int monthOfYear = 1;
    int dayOfMonth = 1;
    int hourOfDay = 0;
    int minuteOfHour = 0;
    int secondOfMinute = 0;
    String xm = "";
    String xs = "";
    String format = getDateFormat();
    int len = string.length();
    switch (len) {
    case 22:
        xm = string.substring(20);
    case 19:
        if (xm.isEmpty()) {
            xs = string.substring(17, 19);
        }
        if (xs.equalsIgnoreCase("AM") || xs.equalsIgnoreCase("PM")) {
            xm = xs;
        } else {
            secondOfMinute = Integer.parseInt(string.substring(17, 19));
        }
    case 16:
        minuteOfHour = Integer.parseInt(string.substring(14, 16));
        hourOfDay = Integer.parseInt(string.substring(11, 13));
        if (xm.equalsIgnoreCase("AM") && hourOfDay == 12) {
            hourOfDay = 0;
        }
        if (xm.equalsIgnoreCase("PM") && hourOfDay <= 11) {
            hourOfDay += 12;
        }
        format = getTimestampFormat();
    case 10:
        switch (format.substring(0, 2)) {
        case "yy":
            year = Integer.parseInt(string.substring(0, 4));
            monthOfYear = Integer.parseInt(string.substring(5, 7));
            dayOfMonth = Integer.parseInt(string.substring(8, 10));
            break;
        case "MM":
            year = Integer.parseInt(string.substring(6, 10));
            monthOfYear = Integer.parseInt(string.substring(0, 2));
            dayOfMonth = Integer.parseInt(string.substring(3, 5));
            break;
        case "dd":
        default:
            year = Integer.parseInt(string.substring(6, 10));
            monthOfYear = Integer.parseInt(string.substring(3, 5));
            dayOfMonth = Integer.parseInt(string.substring(0, 2));
            break;
        }
        break;
    case 8:
        xm = string.substring(6);
    case 6:
        minuteOfHour = Integer.parseInt(string.substring(3, 5));
        hourOfDay = Integer.parseInt(string.substring(0, 2));
        if (xm.equalsIgnoreCase("AM") && hourOfDay == 12) {
            hourOfDay = 0;
        }
        if (xm.equalsIgnoreCase("PM") && hourOfDay <= 11) {
            hourOfDay += 12;
        }
        break;
    default:
        return null;
    }
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, monthOfYear - 1);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minuteOfHour);
    c.set(Calendar.SECOND, secondOfMinute);
    c.set(Calendar.MILLISECOND, 0);
    return new Date(c.getTimeInMillis());
}

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

/**
 * Save the updated credit bean./* ww  w. j a  va  2s .c om*/
 *
 * @param credit the credit
 * @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 CreditBean credit, final UserBean checkUser, final PrivilegesBean privileges,
        final String action) throws WhichDoctorDaoException {

    // Create credit requires all the essential information to be supplied
    if (credit.getDescription() == null) {
        throw new WhichDoctorDaoException("Credit description field " + "cannot be null");
    }
    if (StringUtils.isBlank(credit.getDescription())) {
        throw new WhichDoctorDaoException("Credit description field cannot " + "be an empty string");
    }
    if (credit.getTypeName() == null) {
        throw new WhichDoctorDaoException("Credit requires a credit type");
    }
    if (StringUtils.isBlank(credit.getTypeName())) {
        throw new WhichDoctorDaoException("Credit requires a credit type");
    }
    if (StringUtils.equals(credit.getTypeName(), "Null")) {
        throw new WhichDoctorDaoException("Credit requires a credit type");
    }
    if (credit.getValue() == 0) {
        throw new WhichDoctorDaoException("The credit requires a value");
    }
    if (credit.getPersonId() == 0 && credit.getOrganisationId() == 0) {
        throw new WhichDoctorDaoException("Credit must be attributed to " + "a person or organisation");
    }
    if (!privileges.getPrivilege(checkUser, "credits", action)) {
        throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " credit");
    }

    int typeId = 0;
    try {
        FinancialTypeBean financialObject = financialTypeDAO.load("Credit", credit.getTypeName(),
                credit.getClassName());
        typeId = financialObject.getFinancialTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading financial type for credit: " + e.getMessage());
        throw new WhichDoctorDaoException("Credit requires a valid type");
    }

    int existingDebitGUID = 0;
    // Load the existing credit (if GUID > 0) to check if the
    // associated debit has changed.
    if (credit.getGUID() > 0) {
        try {
            final BuilderBean existingDetails = new BuilderBean();
            existingDetails.setParameter("DEBITS_FULL", true);
            final CreditBean existingCredit = this.loadGUID(credit.getGUID(), existingDetails);
            if (existingCredit.getDebit() != null) {
                existingDebitGUID = existingCredit.getDebit().getGUID();
            }
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error loading existing credit: " + wde.getMessage());
        }
    }

    /* Check if the credit number exists, if not create one */
    credit.setNumber(this.checkNumber("credit", credit.getNumber(), credit.getIssued()));

    int creditId = 0;

    /* Does a credit number need to be generated */
    Date issued = new Date(Calendar.getInstance().getTimeInMillis());
    if (credit.getIssued() != null) {
        issued = new Date(credit.getIssued().getTime());
    }

    DebitBean debit = credit.getDebit();
    if (debit == null) {
        debit = new DebitBean();
    }
    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(credit.getDescription());
    parameters.add(credit.getNumber());
    parameters.add(credit.getCancelled());
    parameters.add(credit.getGSTRate());
    parameters.add(credit.getValue());
    parameters.add(credit.getNetValue());
    parameters.add(credit.getPersonId());
    parameters.add(credit.getOrganisationId());
    parameters.add(issued);
    parameters.add(typeId);
    parameters.add(debit.getGUID());
    parameters.add(credit.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(credit.getLogMessage(action));

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

    if (creditId > 0) {
        dataLogger.info(checkUser.getDN() + " created creditId: " + String.valueOf(creditId));

        // Update the financial summary
        updateFinancialSummary(action, credit, typeId, issued);

        // Update the related debit's calculated values
        if (existingDebitGUID > 0) {
            // Update the previous debit GUID
            this.getDebitDAO().refreshDebitValues(existingDebitGUID);
        }
        if (debit.getGUID() > 0 && debit.getGUID() != existingDebitGUID) {
            this.getDebitDAO().refreshDebitValues(debit.getGUID());
        }

        // Update the search index
        if (credit.getOrganisationId() > 0) {
            this.getSearchIndexDAO().updateCurrentBalanceIndex(credit.getOrganisationId(), "organisation");
        } else {
            this.getSearchIndexDAO().updateCurrentBalanceIndex(credit.getPersonId(), "person");
        }
    }
    return creditId;
}

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

/**
 * In this test, single concept RDF is imported. concept is a non existing concept to be imported with data elements
 *
 * @throws Exception/*from   w ww. ja  va2 s  .  c  o  m*/
 */
@Test
@Rollback
public void testIfNewConceptAdded() 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 RDF file
    Reader reader = getReaderFromResource("rdf_import/rdf_import_test_3.rdf");

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

    // manually create values of new concept for comparison
    VocabularyConcept vc11 = new VocabularyConcept();
    // vc11.setId(11); //this field will be updated after re-querying
    vc11.setIdentifier("rdf_test_concept_4");
    vc11.setLabel("rdf_test_concept_label_4");
    vc11.setDefinition("rdf_test_concept_def_4");
    vc11.setStatus(StandardGenericStatus.VALID);
    vc11.setStatusModified(new Date(System.currentTimeMillis()));
    vc11.setAcceptedDate(new Date(System.currentTimeMillis()));

    // create element attributes (there is only one concept)
    List<List<DataElement>> elementAttributes = new ArrayList<List<DataElement>>();
    DataElement elem = null;
    String identifier = null;
    int dataElemId = -1;

    // skos:prefLabel
    identifier = "skos:prefLabel";
    dataElemId = 8;
    List<DataElement> elements = new ArrayList<DataElement>();
    elem = new DataElement();
    elem.setId(dataElemId);
    elem.setIdentifier(identifier);
    elem.setAttributeValue("bg_rdf_test_concept_4");
    elem.setAttributeLanguage("bg");
    elements.add(elem);
    elem = new DataElement();
    elem.setId(dataElemId);
    elem.setIdentifier(identifier);
    elem.setAttributeValue("bg2_rdf_test_concept_4");
    elem.setAttributeLanguage("bg");
    elements.add(elem);
    elementAttributes.add(elements);

    // skos:definition
    identifier = "skos:definition";
    dataElemId = 9;
    elements = new ArrayList<DataElement>();
    elem = new DataElement();
    elem.setId(dataElemId);
    elem.setIdentifier(identifier);
    elem.setAttributeValue("de_rdf_test_concept_4");
    elem.setAttributeLanguage("de");
    elements.add(elem);
    elementAttributes.add(elements);

    vc11.setElementAttributes(elementAttributes);
    concepts.add(vc11);

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

    // last object should be the inserted one, so use it is id to set (all other fields are updated manually)
    vc11.setId(updatedConcepts.get(3).getId());

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

From source file:gov.nih.nci.integration.caaers.CaAERSParticipantStrategyTest.java

/**
 * Tests rollback() of Register Participant using the ServiceInvocationStrategy class for success case
 * /*from ww w.  j a  v a2 s .  co  m*/
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 * @throws MalformedURLException - MalformedURLException
 * @throws SOAPFaultException - SOAPFaultException
 * 
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void rollbackRegisterParticipantSuccess()
        throws IntegrationException, SOAPFaultException, MalformedURLException, JAXBException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            return getParticipantXMLString();
        }
    }).anyTimes();

    final CaaersServiceResponse caaersServiceResponse = getDeleteParticipantResponse(SUCCESS);
    EasyMock.expect(wsClient.deleteParticipant((String) EasyMock.anyObject())).andReturn(caaersServiceResponse);
    EasyMock.replay(wsClient);

    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getParticipantInterimMessage(), stTime,
            caAERSRegistrationServiceInvocationStrategy.getStrategyIdentifier());

    final ServiceInvocationResult result = caAERSRegistrationServiceInvocationStrategy
            .rollback(serviceInvocationMessage);

    Assert.assertNotNull(result);
}

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

@Override
public void insert(final OpenbareRuimte openbareRuimte) throws DAOException {
    try {//from  w  w  w  . j a v a 2  s .  c o  m
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement("insert into bag_openbare_ruimte ("
                        + "bag_openbare_ruimte_id," + "aanduiding_record_inactief,"
                        + "aanduiding_record_correctie," + "openbare_ruimte_naam," + "officieel,"
                        + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek,"
                        + "openbare_ruimte_type," + "bron_documentdatum," + "bron_documentnummer,"
                        + "openbareruimte_status," + "bag_woonplaats_id," + "verkorte_openbare_ruimte_naam"
                        + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                ps.setLong(1, openbareRuimte.getIdentificatie());
                ps.setInt(2, openbareRuimte.getAanduidingRecordInactief().ordinal());
                ps.setLong(3, openbareRuimte.getAanduidingRecordCorrectie());
                ps.setString(4, openbareRuimte.getOpenbareRuimteNaam());
                ps.setInt(5, openbareRuimte.getOfficieel().ordinal());
                ps.setTimestamp(6, new Timestamp(openbareRuimte.getBegindatumTijdvakGeldigheid().getTime()));
                if (openbareRuimte.getEinddatumTijdvakGeldigheid() == null)
                    ps.setNull(7, Types.TIMESTAMP);
                else
                    ps.setTimestamp(7, new Timestamp(openbareRuimte.getEinddatumTijdvakGeldigheid().getTime()));
                ps.setInt(8, openbareRuimte.getInOnderzoek().ordinal());
                ps.setInt(9, openbareRuimte.getOpenbareRuimteType().ordinal());
                ps.setDate(10, new Date(openbareRuimte.getDocumentdatum().getTime()));
                ps.setString(11, openbareRuimte.getDocumentnummer());
                ps.setInt(12, openbareRuimte.getOpenbareruimteStatus().ordinal());
                ps.setLong(13, openbareRuimte.getGerelateerdeWoonplaats());
                ps.setString(14, openbareRuimte.getVerkorteOpenbareRuimteNaam());
                return ps;
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting openbare ruimte: " + openbareRuimte.getIdentificatie(), e);
    }
}

From source file:org.apache.hadoop.hive.serde2.avro.AvroDeserializer.java

private Object deserializePrimitive(Object datum, Schema fileSchema, Schema recordSchema,
        PrimitiveTypeInfo columnType) throws AvroSerdeException {
    switch (columnType.getPrimitiveCategory()) {
    case STRING://  w w w .ja  v a  2 s.  c  o  m
        return datum.toString(); // To workaround AvroUTF8
    // This also gets us around the Enum issue since we just take the value
    // and convert it to a string. Yay!
    case BINARY:
        if (recordSchema.getType() == Type.FIXED) {
            Fixed fixed = (Fixed) datum;
            return fixed.bytes();
        } else if (recordSchema.getType() == Type.BYTES) {
            return AvroSerdeUtils.getBytesFromByteBuffer((ByteBuffer) datum);
        } else {
            throw new AvroSerdeException(
                    "Unexpected Avro schema for Binary TypeInfo: " + recordSchema.getType());
        }
    case DECIMAL:
        if (fileSchema == null) {
            throw new AvroSerdeException(
                    "File schema is missing for decimal field. Reader schema is " + columnType);
        }

        int scale = 0;
        try {
            scale = fileSchema.getJsonProp(AvroSerDe.AVRO_PROP_SCALE).getIntValue();
        } catch (Exception ex) {
            throw new AvroSerdeException("Failed to obtain scale value from file schema: " + fileSchema, ex);
        }

        HiveDecimal dec = AvroSerdeUtils.getHiveDecimalFromByteBuffer((ByteBuffer) datum, scale);
        JavaHiveDecimalObjectInspector oi = (JavaHiveDecimalObjectInspector) PrimitiveObjectInspectorFactory
                .getPrimitiveJavaObjectInspector((DecimalTypeInfo) columnType);
        return oi.set(null, dec);
    case CHAR:
        if (fileSchema == null) {
            throw new AvroSerdeException(
                    "File schema is missing for char field. Reader schema is " + columnType);
        }

        int maxLength = 0;
        try {
            maxLength = fileSchema.getJsonProp(AvroSerDe.AVRO_PROP_MAX_LENGTH).getValueAsInt();
        } catch (Exception ex) {
            throw new AvroSerdeException(
                    "Failed to obtain maxLength value for char field from file schema: " + fileSchema, ex);
        }

        String str = datum.toString();
        HiveChar hc = new HiveChar(str, maxLength);
        return hc;
    case VARCHAR:
        if (fileSchema == null) {
            throw new AvroSerdeException(
                    "File schema is missing for varchar field. Reader schema is " + columnType);
        }

        maxLength = 0;
        try {
            maxLength = fileSchema.getJsonProp(AvroSerDe.AVRO_PROP_MAX_LENGTH).getValueAsInt();
        } catch (Exception ex) {
            throw new AvroSerdeException(
                    "Failed to obtain maxLength value for varchar field from file schema: " + fileSchema, ex);
        }

        str = datum.toString();
        HiveVarchar hvc = new HiveVarchar(str, maxLength);
        return hvc;
    case DATE:
        if (recordSchema.getType() != Type.INT) {
            throw new AvroSerdeException("Unexpected Avro schema for Date TypeInfo: " + recordSchema.getType());
        }

        return new Date(DateWritable.daysToMillis((Integer) datum));
    case TIMESTAMP:
        if (recordSchema.getType() != Type.LONG) {
            throw new AvroSerdeException("Unexpected Avro schema for Date TypeInfo: " + recordSchema.getType());
        }
        return new Timestamp((Long) datum);
    default:
        return datum;
    }
}