Example usage for java.sql Date Date

List of usage examples for java.sql Date Date

Introduction

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

Prototype

public Date(long date) 

Source Link

Document

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

Usage

From source file:com.oinux.lanmitm.util.RequestParser.java

public static ArrayList<BasicClientCookie> parseRawCookie(String rawCookie) {
    String[] rawCookieParams = rawCookie.split(";");
    ArrayList<BasicClientCookie> cookies = new ArrayList<BasicClientCookie>();

    for (String rawCookieParam : rawCookieParams) {
        String[] rawCookieNameAndValue = rawCookieParam.split("=");

        if (rawCookieNameAndValue.length != 2)
            continue;

        String cookieName = rawCookieNameAndValue[0].trim();
        String cookieValue = rawCookieNameAndValue[1].trim();
        BasicClientCookie cookie = new BasicClientCookie(cookieName, cookieValue);

        for (int i = 1; i < rawCookieParams.length; i++) {
            String rawCookieParamNameAndValue[] = rawCookieParams[i].trim().split("=");
            String paramName = rawCookieParamNameAndValue[0].trim();

            if (paramName.equalsIgnoreCase("secure"))
                cookie.setSecure(true);/* w  ww . ja va2  s.c om*/

            else {
                // attribute not a flag or missing value.
                if (rawCookieParamNameAndValue.length == 2) {
                    String paramValue = rawCookieParamNameAndValue[1].trim();
                    if (paramName.equalsIgnoreCase("max-age")) {
                        long maxAge = Long.parseLong(paramValue);
                        Date expiryDate = new Date(java.lang.System.currentTimeMillis() + maxAge);
                        cookie.setExpiryDate(expiryDate);
                    } else if (paramName.equalsIgnoreCase("domain"))
                        cookie.setDomain(paramValue);
                    else if (paramName.equalsIgnoreCase("path"))
                        cookie.setPath(paramValue);
                    else if (paramName.equalsIgnoreCase("comment"))
                        cookie.setComment(paramValue);
                }
            }
        }
        cookies.add(cookie);
    }
    return cookies;
}

From source file:com.zimbra.qa.unittest.TestImap.java

@Test
public void testAppend() throws Exception {
    assertTrue(connection.hasCapability("UIDPLUS"));
    Flags flags = Flags.fromSpec("afs");
    Date date = new Date(System.currentTimeMillis());
    Literal msg = message(100000);//from   w w  w. j  a v  a2s . c  o  m
    try {
        AppendResult res = connection.append("INBOX", flags, date, msg);
        assertNotNull(res);
        byte[] b = fetchBody(res.getUid());
        assertArrayEquals("content mismatch", msg.getBytes(), b);
    } finally {
        msg.dispose();
    }
}

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

/**
 * Save the updated MembershipBean./*from  www. j  a v  a2 s.c  om*/
 *
 * @param membership the membership
 * @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 MembershipBean membership, final UserBean checkUser, final PrivilegesBean privileges,
        final String action) throws WhichDoctorDaoException {

    /* Check required information within membership bean is present */
    if (membership.getMembershipClass() == null) {
        throw new WhichDoctorDaoException("Membership class cannot be null");
    }
    if (StringUtils.isBlank(membership.getMembershipClass())) {
        throw new WhichDoctorDaoException("Membership class cannot be an empty string");
    }
    if (membership.getMembershipType() == null) {
        throw new WhichDoctorDaoException("Membership type cannot be null");
    }
    if (membership.getReferenceGUID() == 0) {
        throw new WhichDoctorDaoException("Membership requires a valid Reference GUID number");
    }
    if (!privileges.getPrivilege(checkUser, "membership", action)) {
        throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " membership entry");
    }

    int membershipTypeId = 0;
    try {
        ObjectTypeBean object = this.getObjectTypeDAO().load("Membership", membership.getMembershipType(),
                membership.getMembershipClass());
        membershipTypeId = object.getObjectTypeId();
    } catch (Exception e) {
        dataLogger.error("Error loading objecttype for membership type: " + e.getMessage());
    }
    if (membershipTypeId == 0) {
        throw new WhichDoctorDaoException("Membership type not found");
    }

    int membershipId = 0;

    /* Load objecttypeIds */
    HashMap<Integer, Integer> objectTypeIds = new HashMap<Integer, Integer>();

    for (int i = 1; i <= MAX_OBJECTTYPES; i++) {
        /* By default set the objectTypeId value to 0 */
        objectTypeIds.put(new Integer(i), new Integer(0));
        if (membership.getObjectTypeField(i) != null) {
            try {
                ObjectTypeBean object = membership.getObjectTypeField(i);
                ObjectTypeBean loadedObject = this.getObjectTypeDAO().load(object.getObject(), object.getName(),
                        object.getClassName());
                objectTypeIds.put(new Integer(i), new Integer(loadedObject.getObjectTypeId()));
            } catch (Exception e) {
                dataLogger.error("Error loading objecttype Id: " + e.getMessage());
            }
        }
    }

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(membership.getReferenceGUID());
    parameters.add(membershipTypeId);
    parameters.add(membership.getMemo());
    parameters.add(membership.getJoinedDate());
    parameters.add(membership.getLeftDate());
    parameters.add(membership.getPrimary());

    /* Set integer fields */
    for (int i = 1; i <= MAX_INTEGERS; i++) {
        parameters.add(membership.getIntField(i));
    }

    /* Set objecttype fields */
    for (int i = 1; i <= MAX_OBJECTTYPES; i++) {
        parameters.add(objectTypeIds.get(i));
    }

    /* Set String fields */
    for (int i = 1; i <= MAX_CHARS; i++) {
        parameters.add(membership.getCharField(i));
    }

    /* Set date fields */
    for (int i = 1; i <= MAX_DATES; i++) {
        Date membershipDate = null;

        if (membership.getDateField(i) != null) {
            membershipDate = new Date(membership.getDateField(i).getTime());
        }
        parameters.add(membershipDate);
    }

    /* The general details about this membership field */
    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
    parameters.add(membership.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(membership.getLogMessage(action));

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

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

    if (membershipId > 0) {
        /* Update primary flag to reflect modification */
        updatePrimary(membership, action);

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

    }
    return membershipId;
}

From source file:org.zht.framework.service.impl.BaseServiceImpl.java

private void generateCurrentTimeStamp(M m) {
    Field[] fields = m.getClass().getDeclaredFields();
    if (fields == null || fields.length == 0) {
        return;//from w ww .  jav  a2s .  c  om
    }
    for (Field f : fields) {
        if (f.isAnnotationPresent(CurrentTimeStamp.class)) {
            MethodAccess access = MethodAccess.get(m.getClass());
            access.invoke(m, "set" + ZStrUtil.toUpCaseFirst(f.getName()), new Date(System.currentTimeMillis()));
        }
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java

private static Object tryConvertToDataType(Object value, Class<?> toDataType) throws OdaException {
    if (value == null || toDataType.isInstance(value)) // already in specified data type
        return value;

    try {//from w w  w. j  a v a  2s.  c  o m
        if (value instanceof String) {
            String stringValue = (String) value;
            if (toDataType == Integer.class)
                return Integer.valueOf(stringValue);
            if (toDataType == Double.class)
                return Double.valueOf(stringValue);
            if (toDataType == BigDecimal.class)
                return new BigDecimal(stringValue);
            if (toDataType == Boolean.class)
                return Boolean.valueOf(stringValue);
            if (toDataType == Date.class)
                return Date.valueOf(stringValue);
            if (toDataType == Timestamp.class)
                return Timestamp.valueOf(stringValue);
            if (toDataType == byte[].class)
                return tryConvertToBytes(stringValue);
        }

        if (value instanceof java.util.Date) // the object type returned by MongoDB for a Date field
        {
            long msTime = ((java.util.Date) value).getTime();
            if (toDataType == Date.class)
                return new Date(msTime);
            if (toDataType == Timestamp.class)
                return new Timestamp(msTime);
        }

        if (value instanceof BSONTimestamp) {
            long msTime = ((BSONTimestamp) value).getTime() * 1000L;
            if (toDataType == Date.class)
                return new Date(msTime);
            if (toDataType == Timestamp.class)
                return new Timestamp(msTime);
        }

        if (toDataType == Integer.class)
            return tryConvertToInteger(value);
        if (toDataType == Double.class)
            return tryConvertToDouble(value);
        if (toDataType == Boolean.class)
            return tryConvertToBoolean(value);
    } catch (Exception ex) {
        String errMsg = Messages.bind(Messages.mDbResultSet_cannotConvertFieldData, new Object[] {
                DriverUtil.EMPTY_STRING, value, value.getClass().getSimpleName(), toDataType.getSimpleName() });
        getLogger().severe(errMsg);

        OdaException odaEx = new OdaException(errMsg);
        odaEx.initCause(ex);
        throw odaEx;
    }

    // non-handled data type conversion; return value as is
    return value;
}

From source file:com.school.exam.web.student.StudentController.java

@RequestMapping(value = "answer", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
@ResponseBody/*from   ww  w . ja  va2s  .c  o m*/
public String answerFile(AnswerVO answerVO, HttpServletRequest request) {

    logger.debug("upload path:{}->file:{}", request.getRealPath("/"), answerVO.getFile().getName());

    String logoRealPathDir = request.getSession().getServletContext().getRealPath("/static/temp");

    /**?**/
    File logoSaveFile = new File(logoRealPathDir);
    if (!logoSaveFile.exists())
        logoSaveFile.mkdirs();

    Long currentMillis = System.currentTimeMillis();

    String suffix = answerVO.getFile().getOriginalFilename()
            .substring(answerVO.getFile().getOriginalFilename().lastIndexOf("."));

    Answer answerObj = new Answer();

    String course = answerVO.getCourse();
    if (null != course) {
        course = org.apache.commons.lang3.StringUtils.replace(course, "<br/>", "");
        course = org.apache.commons.lang3.StringUtils.replace(course, " ", "");
    }

    answerObj.setTitle(answerVO.getTitle());
    answerObj.setCourse(course);
    answerObj.setAnswer(answerVO.getFile().getOriginalFilename());
    answerObj.setType(suffix);
    answerObj.setAnswerDate(new Date(currentMillis));

    User user = new User();
    user.setId(getCurrentUserId());

    answerObj.setUser(user);

    answerService.save(answerObj);

    String fileName = logoRealPathDir + File.separator + answerObj.getUser().getId() + "-"
            + answerObj.getAnswer();
    File file = new File(fileName);

    try {
        answerVO.getFile().transferTo(file);
    } catch (IOException e) {
        logger.warn("save file error!", e);
    }
    return "true";
}

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

/**
 * Save.//from w  ww  .  j a v  a  2s. c o m
 *
 * @param payment the payment
 * @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 PaymentBean payment, final ReceiptBean receipt, final UserBean checkUser,
        final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException {

    /* Check required information within PaymentBean is present */
    if (payment.getReferenceGUID() == 0) {
        throw new WhichDoctorDaoException("Payment requires a valid " + "Reference GUID number");
    }
    if (receipt.getId() == 0) {
        throw new WhichDoctorDaoException("Payment requires a valid receipt");
    }
    if (!privileges.getPrivilege(checkUser, "payments", action)) {
        throw new WhichDoctorDaoException("Insufficient user credentials " + "to create new payment entry");
    }

    /* Get the Receipt 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("Error loading financial type " + "for receipt: " + e.getMessage());
    }

    if (payment.getIncomeStreamId() > 0 && payment.getNetValue() > 0) {
        // Debit should not exist if payment is negative This is because you
        // cannot attribute negative payment to a debit
        payment.setDebit(new DebitBean());

        // As it is a negative debit the net value should be negative
        payment.setNetValue(0 - payment.getNetValue());
        // Reset the value in order to recalculate GST (if applicable)
        payment.setValue(0);
    }

    int personGUID = 0;
    int organisationGUID = 0;
    if (payment.getPerson() != null) {
        personGUID = payment.getPerson().getGUID();
    }
    if (payment.getOrganisation() != null) {
        organisationGUID = payment.getOrganisation().getGUID();
    }

    int newDebitGUID = 0;
    if (payment.getDebit() != null) {
        // Load the debit to get the GST rate
        try {
            final DebitBean debit = this.debitDAO.loadGUID(payment.getDebit().getGUID());
            if (debit != null) {
                payment.setGSTRate(debit.getGSTRate());
                newDebitGUID = debit.getGUID();

                if (personGUID == 0 && debit.getPerson() != null) {
                    personGUID = debit.getPerson().getGUID();
                }
                if (organisationGUID == 0 && debit.getOrganisation() != null) {
                    organisationGUID = debit.getOrganisation().getGUID();
                }
            }
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error loading debit: " + wde.getMessage());
        }
    }

    int existingDebitGUID = 0;
    // Load the existing payment (if GUID > 0) to check if the
    // associated debit has changed.
    if (payment.getGUID() > 0) {
        try {
            final PaymentBean existingPayment = this.loadGUID(payment.getGUID());
            if (existingPayment.getDebit() != null) {
                existingDebitGUID = existingPayment.getDebit().getGUID();
            }
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error loading existing payment: " + wde.getMessage());
        }
    }

    int paymentId = 0;

    Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(payment.getReferenceGUID());
    parameters.add(personGUID);
    parameters.add(organisationGUID);
    parameters.add(newDebitGUID);
    parameters.add(payment.getValue());
    parameters.add(payment.getNetValue());
    parameters.add(payment.getIncomeStreamId());
    parameters.add(payment.getGSTRate());
    parameters.add(payment.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(payment.getLogMessage(action));

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

    if (paymentId > 0) {

        dataLogger.info(checkUser.getDN() + " created paymentId: " + paymentId);
        /* Get Issued Date */
        Date issued = new Date(Calendar.getInstance().getTimeInMillis());
        if (receipt.getIssued() != null) {
            issued = new Date(receipt.getIssued().getTime());
        }

        if (action.compareTo("delete") == 0) {
            /* Delete the financial summary */
            this.getJdbcTemplateWriter().update(this.getSQL().getValue("payment/deleteSummary"),
                    new Object[] { receipt.getGUID(), payment.getGUID() });

        } else {
            /* Create or modify financial summary entry */
            try {
                this.getJdbcTemplateWriter().update(this.getSQL().getValue("payment/editSummary"),
                        new Object[] { receipt.getGUID(), typeId, receipt.getNumber(), receipt.getDescription(),
                                payment.getValue(), payment.getNetValue(), receipt.getCancelled(), issued,
                                personGUID, organisationGUID, payment.getGUID(),

                                typeId, receipt.getDescription(), payment.getValue(), payment.getNetValue(),
                                receipt.getCancelled(), issued, personGUID, organisationGUID });
            } catch (DataAccessException dae) {
                dataLogger.error("Failed to modify the financial summary: " + dae.getMessage());
                throw new WhichDoctorDaoException(
                        "Failed to modify the financial summary: " + dae.getMessage());
            }
        }

        /* Update the related debit's calculated values */
        if (existingDebitGUID > 0) {
            this.debitDAO.refreshDebitValues(existingDebitGUID);
        }
        if (newDebitGUID > 0 && newDebitGUID != existingDebitGUID) {
            this.debitDAO.refreshDebitValues(newDebitGUID);
        }

        /* Update the search index */
        if (organisationGUID > 0) {
            this.searchIndexDAO.updateCurrentBalanceIndex(organisationGUID, "organisation");
        } else {
            this.searchIndexDAO.updateCurrentBalanceIndex(personGUID, "person");
        }
    }
    return paymentId;
}

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

@Override
public void insert(final Pand pand) throws DAOException {
    try {/*  ww  w .  ja v a  2  s .c  om*/
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement("insert into bag_pand (" + "bag_pand_id,"
                        + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "officieel,"
                        + "pand_geometrie," + "bouwjaar," + "pand_status," + "begindatum_tijdvak_geldigheid,"
                        + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum,"
                        + "bron_documentnummer" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)");
                ps.setLong(1, pand.getIdentificatie());
                ps.setInt(2, pand.getAanduidingRecordInactief().ordinal());
                ps.setLong(3, pand.getAanduidingRecordCorrectie());
                ps.setInt(4, pand.getOfficieel().ordinal());
                ps.setString(5, pand.getPandGeometrie());
                ps.setInt(6, pand.getBouwjaar());
                ps.setString(7, pand.getPandStatus());
                ps.setTimestamp(8, new Timestamp(pand.getBegindatumTijdvakGeldigheid().getTime()));
                if (pand.getEinddatumTijdvakGeldigheid() == null)
                    ps.setNull(9, Types.TIMESTAMP);
                else
                    ps.setTimestamp(9, new Timestamp(pand.getEinddatumTijdvakGeldigheid().getTime()));
                ps.setInt(10, pand.getInOnderzoek().ordinal());
                ps.setDate(11, new Date(pand.getDocumentdatum().getTime()));
                ps.setString(12, pand.getDocumentnummer());
                return ps;
            }
        });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting pand: " + pand.getIdentificatie(), e);
    }
}

From source file:com.zimbra.qa.unittest.TestImap.java

@Test
public void testOverflowAppend() throws Exception {
    assertTrue(connection.hasCapability("UIDPLUS"));
    int oldReadTimeout = connection.getConfig().getReadTimeout();
    try {//from w w w  .ja v a  2 s  .  c  om
        connection.setReadTimeout(10);
        Flags flags = Flags.fromSpec("afs");
        Date date = new Date(System.currentTimeMillis());
        ImapRequest req = connection.newRequest(CAtom.APPEND, new MailboxName("INBOX"));
        req.addParam("{" + ((long) (Integer.MAX_VALUE) + 1) + "+}");
        ImapResponse resp = req.send();
        assertTrue(resp.isNO() || resp.isBAD());

        req = connection.newRequest(CAtom.APPEND, new MailboxName("INBOX"));
        req.addParam("{" + ((long) (Integer.MAX_VALUE) + 1) + "}");
        resp = req.send();
        assertTrue(resp.isNO() || resp.isBAD());
    } finally {
        connection.setReadTimeout(oldReadTimeout);
    }
}

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 = OK./*from  w  ww  .  j  av a2  s . c o m*/
 * <br/> filelist_checkdatetime = current time.
 *
 * @param replicafileinfoId The id of the replicafileinfo.
 * @param con An open connection to the archive database
 */
protected static void updateReplicaFileInfoFilelist(long replicafileinfoId, Connection con) {
    PreparedStatement statement = null;
    try {
        // The SQL statement
        final String sql = "UPDATE replicafileinfo SET filelist_status = ?, " + "filelist_checkdatetime = ? "
                + "WHERE replicafileinfo_guid = ?";

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

        // complete the SQL statement.
        statement = DBUtils.prepareStatement(con, sql, FileListStatus.OK.ordinal(), now, 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);
    }
}