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.castor.jdo.engine.SQLTypeInfos.java

/**
 * Set given value on given PreparedStatement at given index with given SQL type.
 * //ww  w. java  2 s  . c om
 * @param stmt The PreparedStatement to set value on.
 * @param index The index of the value in the PreparedStatement.
 * @param value The value to set.
 * @param sqlType The SQL type of the value.
 */
public static void setValue(final PreparedStatement stmt, final int index, final Object value,
        final int sqlType) {
    try {
        if (value == null) {
            stmt.setNull(index, sqlType);
        } else {
            // Special processing for BLOB and CLOB types, because they are mapped
            // by Castor to java.io.InputStream and java.io.Reader, respectively,
            // while JDBC driver expects java.sql.Blob and java.sql.Clob.
            switch (sqlType) {
            case Types.FLOAT:
            case Types.DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case Types.REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case Types.TIME:
                final Time time = value instanceof java.util.Date ? new Time(((java.util.Date) value).getTime())
                        : null;
                stmt.setTime(index, time != null ? time : (Time) value, getCalendar());
                break;
            case Types.DATE:
                final Date date = value instanceof java.util.Date ? new Date(((java.util.Date) value).getTime())
                        : null;
                stmt.setDate(index, date != null ? date : (Date) value);
                break;
            case Types.TIMESTAMP:
                final Timestamp timestamp = value instanceof java.util.Date
                        ? new Timestamp(((java.util.Date) value).getTime())
                        : null;
                stmt.setTimestamp(index, timestamp != null ? timestamp : (Timestamp) value, getCalendar());
                break;
            case Types.BLOB:
                try {
                    InputStream stream;
                    if (value instanceof byte[]) {
                        stream = new ByteArrayInputStream((byte[]) value);
                    } else {
                        stream = (InputStream) value;
                    }
                    stmt.setBinaryStream(index, stream, stream.available());
                } catch (IOException ex) {
                    throw new SQLException(ex.toString());
                }
                break;
            case Types.CLOB:
                if (value instanceof String) {
                    stmt.setCharacterStream(index, new StringReader((String) value),
                            Math.min(((String) value).length(), Integer.MAX_VALUE));
                } else {
                    stmt.setCharacterStream(index, ((Clob) value).getCharacterStream(),
                            (int) Math.min(((Clob) value).length(), Integer.MAX_VALUE));
                }
                break;
            default:
                stmt.setObject(index, value, sqlType);
                break;
            }
        }
    } catch (SQLException ex) {
        LOG.error("Unexpected SQL exception: ", ex);
    }
}

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

/**
 * Tests Update Participant Registration using the ServiceInvocationStrategy class for a scenario when
 * getParticipant() is failed//w w  w. j  av  a  2  s.c om
 * 
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 * @throws MalformedURLException - MalformedURLException
 * @throws SOAPFaultException - SOAPFaultException
 * @throws DatatypeConfigurationException - DatatypeConfigurationException
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void updateParticipantRegistrationGetParticipantFailure() throws IntegrationException,
        SOAPFaultException, MalformedURLException, JAXBException, DatatypeConfigurationException {
    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 updateResponse = getUpdateParticipantResponse(SUCCESS);
    final CaaersServiceResponse getResponse = getParticipantResponse(FAILURE);
    EasyMock.expect(wsClient.updateParticipant((String) EasyMock.anyObject())).andReturn(updateResponse)
            .anyTimes();
    EasyMock.expect(wsClient.getParticipant((String) EasyMock.anyObject())).andReturn(getResponse);
    EasyMock.replay(wsClient);

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

    final ServiceInvocationResult result = caAERSUpdateRegistrationServiceInvocationStrategy
            .invoke(serviceInvocationMessage);

    Assert.assertNotNull(result);
}

From source file:com.sinet.gage.delta.DomainUpdatesImporter.java

private Date getDateFormat(String date) {
    Date formattedDate = null;/* www  .j a  v a 2 s  .c  om*/
    try {
        if (date != null) {
            formattedDate = new Date(dateFormat.parse(date).getTime());
        }
    } catch (ParseException e) {
        log.error("Invalid date format: " + e.getMessage());
    }
    return formattedDate;
}

From source file:org.kuali.coeus.common.budget.impl.summary.BudgetSummaryServiceImpl.java

@Override
public List<BudgetPeriod> generateBudgetPeriods(Budget budget) {
    List<BudgetPeriod> budgetPeriods = new ArrayList<BudgetPeriod>();
    Date projectStartDate = budget.getStartDate();
    Date projectEndDate = budget.getEndDate();
    boolean budgetPeriodExists = true;

    Calendar cl = Calendar.getInstance();

    Date periodStartDate = projectStartDate;
    int budgetPeriodNum = 1;
    while (budgetPeriodExists) {
        cl.setTime(periodStartDate);/*ww  w .  j  a  v  a2 s . c om*/
        cl.add(Calendar.YEAR, 1);
        Date nextPeriodStartDate = new Date(cl.getTime().getTime());
        cl.add(Calendar.DATE, -1);
        Date periodEndDate = new Date(cl.getTime().getTime());
        /* check period end date gt project end date */
        switch (periodEndDate.compareTo(projectEndDate)) {
        case 1:
            periodEndDate = projectEndDate;
        case 0:
            budgetPeriodExists = false;
            break;
        }
        BudgetPeriod budgetPeriod = budget.getNewBudgetPeriod();
        budgetPeriod.setBudgetPeriod(budgetPeriodNum);
        budgetPeriod.setStartDate(periodStartDate);
        budgetPeriod.setEndDate(periodEndDate);
        budgetPeriod.setBudget(budget);

        budgetPeriods.add(budgetPeriod);
        periodStartDate = nextPeriodStartDate;
        budgetPeriodNum++;
    }
    return budgetPeriods;
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UMLSHistoryFileToSQL.java

/**
 * This method converts a date in string format to java.sql.Date Format.
 * //from   w  w  w. ja va  2  s. c  o m
 * @param sDate
 * @param format
 * @return
 * @throws Exception
 */
public static Date convertStringToDate(String sDate, String format) throws Exception {
    java.util.Date dateUtil = null;

    SimpleDateFormat dateformat = new SimpleDateFormat(format);
    try {
        dateUtil = dateformat.parse(sDate);
    } catch (ParseException e) {
        throw new Exception("Exception while parsing the date: " + e.getMessage());
    }

    return new Date(dateUtil.getTime());
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java

private Object converDateTypes(Object val, HCatFieldSchema hfs) {
    HCatFieldSchema.Type hfsType = hfs.getType();
    Date d;/*from ww  w  . j  a  va2 s  .  co m*/
    Time t;
    Timestamp ts;
    if (val instanceof java.sql.Date) {
        d = (Date) val;
        if (hfsType == HCatFieldSchema.Type.DATE) {
            return d;
        } else if (hfsType == HCatFieldSchema.Type.TIMESTAMP) {
            return new Timestamp(d.getTime());
        } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
            return (d.getTime());
        } else if (hfsType == HCatFieldSchema.Type.STRING) {
            return val.toString();
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.CHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hChar = new HiveChar(val.toString(), cti.getLength());
            return hChar;
        }
    } else if (val instanceof java.sql.Time) {
        t = (Time) val;
        if (hfsType == HCatFieldSchema.Type.DATE) {
            return new Date(t.getTime());
        } else if (hfsType == HCatFieldSchema.Type.TIMESTAMP) {
            return new Timestamp(t.getTime());
        } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
            return ((Time) val).getTime();
        } else if (hfsType == HCatFieldSchema.Type.STRING) {
            return val.toString();
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.CHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hChar = new HiveChar(val.toString(), cti.getLength());
            return hChar;
        }
    } else if (val instanceof java.sql.Timestamp) {
        ts = (Timestamp) val;
        if (hfsType == HCatFieldSchema.Type.DATE) {
            return new Date(ts.getTime());
        } else if (hfsType == HCatFieldSchema.Type.TIMESTAMP) {
            return ts;
        } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
            return ts.getTime();
        } else if (hfsType == HCatFieldSchema.Type.STRING) {
            return val.toString();
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.CHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hc = new HiveChar(val.toString(), cti.getLength());
            return hc;
        }
    }
    return null;
}

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

/**
 * Anwesenheit einer Klasse an einem bestimmten Tag abfragen Adresse
 * /api/v1/anwesenheit/{Name der Klasse}/{Datum}
 *
 * @param kl Name der Klasse/*from   w ww . ja  v a 2 s  .c  om*/
 * @param from Das Datum
 * @return Liste von Anwesenheitsobjekten
 */
@GET
@Path("/{klasse}/{from}")
public List<AnwesenheitObjekt> getAnwesenheit(@PathParam("klasse") String kl, @PathParam("from") Date from) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    Date d = new Date(from.getTime() + 1000 * 60 * 60 * 24 - 1);
    Log.d("Webservice Anwesenheit GET klasse=" + kl + " from=" + from + " to=" + d);
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse",
            AnwesenheitEintrag.class);
    query.setParameter("paramKName", kl);
    query.setParameter("paramFromDate", from);
    query.setParameter("paramToDate", d);
    List<AnwesenheitEintrag> anwesenheit = query.getResultList();

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

    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:com.sfs.whichdoctor.dao.RotationDAOImpl.java

/**
 * Load the current rotations for the supplied person GUID.
 *
 * @param personGUID the person guid/* www .  ja  va 2 s . c om*/
 * @param loadDetails the load details
 * @return the collection
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
@SuppressWarnings("unchecked")
public final Collection<RotationBean> loadCurrentForPerson(final int personGUID, final BuilderBean loadDetails)
        throws WhichDoctorDaoException {

    Collection<RotationBean> rotations = new ArrayList<RotationBean>();

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

    final String loadCurrent = getSQL().getValue("rotation/load")
            + " AND rotation.Active = true AND people.Active = true "
            + " AND people.GUID = ? AND rotation.StartDate < ? AND rotation.EndDate > ?";

    try {
        rotations = this.getJdbcTemplateReader().query(loadCurrent,
                new Object[] { personGUID, currentTime, currentTime }, new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return loadRotation(rs, loadDetails);
                    }
                });

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for search: " + ie.getMessage());
    }

    return rotations;
}

From source file:de.fhg.fokus.openride.services.driver.offer.OfferService.java

@PUT
@Produces("text/json")
@Path("{rideId}")
public Response putOffer(@PathParam("rideId") int rideId, String json) {
    ArrayList list = new ArrayList();
    list.add(new Offer());
    list.add(new PostOfferResponse());
    XStream x = Utils.getJasonXStreamer(list);
    Offer r = (Offer) x.fromXML(json);/*from ww w  . j av  a2s .  c  om*/
    //TODO: find evtl. states. If not existant do update and remove old and create new with new infos
    int custid = driverUndertakesRideControllerBean.getDriveByDriveId(rideId).getCustId().getCustId();
    if ((rideId = driverUndertakesRideControllerBean.updateRide(rideId, custid,
            new Point(r.getRidestartPtLon(), r.getRidestartPtLat()),
            new Point(r.getRideendPtLon(), r.getRideendPtLat()), r.getIntermediatePoints(), //Point[] intermediate route points
            new Date(r.getRidestartTime()), StringEscapeUtils.unescapeHtml(r.getRideComment()),
            r.getAcceptableDetourInMin(), r.getAcceptableDetourInKm(), r.getAcceptableDetourInPercent(),
            r.getOfferedSeatsNo(), StringEscapeUtils.unescapeHtml(r.getOfferedCurrency()),
            StringEscapeUtils.unescapeHtml(r.getStartptAddress()),
            StringEscapeUtils.unescapeHtml(r.getEndptAddress()))) == -1) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    } else {

        /**
                
        // TODO: this should be asynchron!!! remove
        List<MatchEntity> matches = lookupRouteMatchingBeanLocal().searchForRiders(rideId);
        de.fhg.fokus.openride.services.driver.offer.helperclasses.MatchResponse  m ;
        List<de.fhg.fokus.openride.services.driver.offer.helperclasses.MatchResponse> list = new ArrayList<de.fhg.fokus.openride.services.driver.offer.helperclasses.MatchResponse>();
        if(matches != null){
        // Some Matches were found.
        for(MatchEntity match: matches){
        int rideid = match.getMatchEntityPK().getRideId();
        int riderrouteid = match.getMatchEntityPK().getRiderrouteId();
        RiderUndertakesRideEntity rideEntity = riderUndertakesRideControllerBean.getRideByRiderRouteId(riderrouteid);
        DriverUndertakesRideEntity driveEntity = driverUndertakesRideControllerBean.getDriveByDriveId(rideid);
                
        CustomerEntity rider = rideEntity.getCustId();
        //this results in a null pointer exception
        //don't know how the jpa translates this query
        //but maybe it misses the match entity in the db
        //it is not yet persistet.
                
        m = new de.fhg.fokus.openride.services.driver.offer.helperclasses.MatchResponse(
        match.getDriverState(),
        match.getRiderState(),
        match.getMatchSharedDistancEmeters(),
        match.getMatchDetourMeters(),
        match.getMatchExpectedStartTime().getTime(),
        driveEntity.getRideId(),
        rideEntity.getRiderrouteId(),
        rider.getCustId(),
        rider.getCustNickname(),
        riderUndertakesRideControllerBean.getRatingsRatioByCustomer(rider),
        match.getMatchPriceCents(),
        rideEntity.getStartptAddress(),
        rideEntity.getEndptAddress()
        );
        list.add(m);
        }
        }
        Response response = Response.ok(x.toXML(list)).build();
         */
        Response response = Response.ok(x.toXML(new PostOfferResponse(rideId))).build();

        //Response response = Response.ok().build();
        return response;
    }
}

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

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

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

    /* Get the typeId */
    int typeId = 0;
    try {
        FinancialTypeBean financialObject = this.financialTypeDAO.load("Receipt", receipt.getTypeName(),
                receipt.getClassName());
        typeId = financialObject.getFinancialTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading financial type for receipt: " + e.getMessage());
        throw new WhichDoctorDaoException("Receipt requires a valid type");
    }
    /* Get the ProcessTypeId */
    int processTypeId = 0;
    try {
        ObjectTypeBean object = this.getObjectTypeDAO().load("Process Type", "", receipt.getProcessType());
        processTypeId = object.getObjectTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading objecttype for process type: " + e.getMessage());
        throw new WhichDoctorDaoException("Receipt requires a valid " + "process type");
    }

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

    int receiptId = 0;

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

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(receipt.getDescription());
    parameters.add(receipt.getNumber());
    parameters.add(processTypeId);
    parameters.add(Integer.parseInt(receipt.getBatchReference()));
    parameters.add(receipt.getBank());
    parameters.add(receipt.getBranch());
    parameters.add(receipt.getCancelled());
    parameters.add(typeId);
    parameters.add(receipt.getPersonId());
    parameters.add(receipt.getOrganisationId());
    parameters.add(issued);
    parameters.add(receipt.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(receipt.getLogMessage(action));

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

    if (receiptId > 0) {

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

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

        postProcessReceiptChange(receipt);
    }

    return receiptId;
}