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:adalid.commons.util.TimeUtils.java

public static Date newDate(java.util.Date date) {
    return date == null ? null : new Date(newDateCalendar(date).getTimeInMillis());
}

From source file:eu.opensourceprojects.mondo.benchmarks.transformationzoo.instantiator.SpecimenGenerator.java

/**
 * @param instanceClass/* w  w w  . ja v a  2  s  . c o  m*/
 */
private Object nextObject(Class<?> instanceClass) {
    if (instanceClass == String.class) {
        return Gpw.generate(generator.nextInt(24) + 1);
    } else if (instanceClass == java.util.Date.class) {
        long dummyTime = generator.nextLong();
        long generatedTime = dummyTime + 2 * 60 * 1000 + generator.nextInt(60 * 1000) + 1;
        return new Date(generatedTime);
    } else {
        log("Do not know how to randomly generate " + instanceClass.getName() + " object");
    }
    return null;
}

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

/**
 * Save the updated DebitBean.//from www.j  ava 2s .  c  om
 *
 * @param debit the debit
 * @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 DebitBean debit, final UserBean checkUser, final PrivilegesBean privileges,
        final String action) throws WhichDoctorDaoException {

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

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

    Double[] calculatedValues = getCalculatedValues(debit);
    final double creditValue = calculatedValues[0];
    final double outstandingValue = calculatedValues[1];

    // Load the existing debit (if one exists) to see if the GST rate has changed
    double existingGSTRate = debit.getGSTRate();
    if (debit.getGUID() > 0) {
        try {
            final DebitBean existingDebit = this.loadGUID(debit.getGUID());
            existingGSTRate = existingDebit.getGSTRate();
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error loading existing debit: " + wde.getMessage());
        }
    }

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

    int debitId = 0;

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

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

    ArrayList<Object> parameters = new ArrayList<Object>();
    parameters.add(debit.getDescription());
    parameters.add(debit.getNumber());
    parameters.add(debit.getGSTRate());
    parameters.add(debit.getCancelled());
    parameters.add(debit.getValue());
    parameters.add(debit.getNetValue());
    parameters.add(creditValue);
    parameters.add(outstandingValue);
    parameters.add(typeId);
    parameters.add(debit.getPersonId());
    parameters.add(debit.getOrganisationId());
    parameters.add(issued);
    parameters.add(debit.getPaymentDue());
    parameters.add(debit.getLatePaymentFee());
    parameters.add(debit.getLatePaymentDate());
    parameters.add(debit.getRecommendedDonation());
    parameters.add(debit.getActive());
    parameters.add(sqlTimeStamp);
    parameters.add(checkUser.getDN());
    parameters.add(debit.getLogMessage(action));

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

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

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

        /* If the existing GST rate is different to the new rate update payments */
        if (debit.getGUID() > 0 && existingGSTRate != debit.getGSTRate()) {
            updateReceiptGst(debit.getGUID(), debit.getGSTRate(), checkUser, privileges);
        }

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

From source file:com.heliumv.api.customer.CustomerApi.java

private boolean setupParamValidityDate(KundenpreislisteParams params, String filterValidityDate) {
    if (StringHelper.isEmpty(filterValidityDate))
        return true;

    try {// w w  w.ja v  a  2s .  c o m
        Calendar c = DatatypeConverter.parseDateTime(filterValidityDate);
        params.setGueltigkeitsDatum(new Date(c.getTimeInMillis()));
        return true;
    } catch (IllegalArgumentException e) {
        System.out.println("illegalargument" + e.getMessage());
    }

    respondBadRequest("filter_validitydate", filterValidityDate);
    return false;
}

From source file:io.heming.accountbook.ui.MainFrame.java

private void searchRecords() {
    String keyword = keywordTextField.getText().trim();
    builder.keyword(keyword);/*ww  w.j  a  va  2s .  c  o m*/
    if (customToggleButton.isSelected()) {
        builder.start(new Date(((java.util.Date) startDateSpinner.getValue()).getTime()))
                .end(new Date(((java.util.Date) endDateSpinner.getValue()).getTime()));
    } else if (yearToggleButton.isSelected()) {
        builder.year();
    } else if (monthToggleButton.isSelected()) {
        builder.month();
    } else {
        builder.day();
    }
    try {
        pages = builder.make();
        if (pages.hasNext()) {
            List<Record> records = pages.next();
            model.setRecords(records);
        } else {
            // ?
            model.setRecords(new ArrayList<>());
        }
        infoLabel.setText(pages.getInfo());
        updateNavStatus();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }
}

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

private Quiz buildQuizFromInputParameters(String data, User user) {
    Quiz quiz = JsonDeserializer.deserialize(data, Quiz.class);
    quiz.setGooruOid(UUID.randomUUID().toString());
    ContentType contentType = getQuizSerivce().getContentType(ContentType.RESOURCE);
    quiz.setContentType(contentType);/*  w w w  .  j  a  v a 2s.  co  m*/
    ResourceType resourceType = getQuizSerivce().getResourceType(ResourceType.Type.QUIZ.getType());
    quiz.setResourceType(resourceType);
    quiz.setLastModified(new Date(System.currentTimeMillis()));
    quiz.setCreatedOn(new Date(System.currentTimeMillis()));
    quiz.setCollectionType(CollectionType.Quiz.getCollectionType());
    if (!hasUnrestrictedContentAccess()) {
        quiz.setSharing(Sharing.PUBLIC.getSharing());
    } else {
        quiz.setSharing(
                quiz.getSharing() != null && (quiz.getSharing().equalsIgnoreCase(Sharing.PRIVATE.getSharing())
                        || quiz.getSharing().equalsIgnoreCase(Sharing.PUBLIC.getSharing())
                        || quiz.getSharing().equalsIgnoreCase(Sharing.ANYONEWITHLINK.getSharing()))
                                ? quiz.getSharing()
                                : Sharing.PUBLIC.getSharing());
    }
    quiz.setUser(user);
    quiz.setOrganization(user.getPrimaryOrganization());
    quiz.setCreator(user);
    quiz.setDistinguish(Short.valueOf("0"));
    quiz.setRecordSource(NOT_ADDED);
    quiz.setIsFeatured(0);
    quiz.setLastUpdatedUserUid(user.getGooruUId());
    return quiz;
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private static Date getDateWithNullValue(java.util.Date date) {
    return (date != null) ? new Date(date.getTime()) : null;
}

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

/**
 * Tests rollback() of Update Participant Registration using the ServiceInvocationStrategy class for success case
 * /*w w  w . j av a2  s.  c o  m*/
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 * @throws MalformedURLException - MalformedURLException
 * @throws SOAPFaultException - SOAPFaultException
 * 
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void rollbackUpdateRegisterParticipantSuccess()
        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 = getUpdateParticipantResponse(SUCCESS);
    EasyMock.expect(wsClient.updateParticipant((String) EasyMock.anyObject())).andReturn(caaersServiceResponse);
    EasyMock.replay(wsClient);

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

    final ServiceInvocationResult result = caAERSUpdateRegistrationServiceInvocationStrategy
            .rollback(serviceInvocationMessage);

    Assert.assertNotNull(result);
}

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 after purge
 *
 * @throws Exception//from ww  w.ja  v a2  s.  co m
 */
@Test
@Rollback
public void testIfNewConceptAddedAfterPurge() 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, true, 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 = new ArrayList<VocabularyConcept>();
    concepts.add(vc11);

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

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

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

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

/**
 * Liste der Fehltage fr einen Schler ber einen Bereich
 *
 * @param httpHeaders auth_key zur Verifikation
 * @param sid ID des Schlers/*from   w ww.j a  va 2 s .c  om*/
 * @param from Bereich von
 * @param to Bereich bis
 * @return Liste von Anwesenheitsobjekten
 */
@GET
@Path("schueler/{sid}/{from}/{to}")
public List<AnwesenheitObjekt> getAnwesenheit(@PathParam("sid") int sid, @PathParam("from") Date from,
        @PathParam("to") Date to) {
    to = new Date(to.getTime() + 24 * 60 * 60 * 1000);
    Log.d("Webservice Anwesenheit GET from=" + from + " to=" + to);
    TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbySchueler",
            AnwesenheitEintrag.class);
    query.setParameter("paramIdSchueler", sid);
    query.setParameter("paramFromDate", from);
    query.setParameter("paramToDate", to);
    List<AnwesenheitEintrag> anwesenheit = query.getResultList();

    Query qb = em.createNamedQuery("findBemerkungbyDate");
    qb.setParameter("paramFromDate", from);
    qb.setParameter("paramToDate", to);
    List<String> ids = new ArrayList<>();
    ids.add("" + sid);
    qb.setParameter("idList", ids);
    List<Bemerkung> bem = qb.getResultList();
    Log.d("Bemerkungen=" + bem);
    return getDataf(anwesenheit, bem);
}