Example usage for java.sql Date getTime

List of usage examples for java.sql Date getTime

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Usage

From source file:su90.mybatisdemo.dao.Job_HistoryMapperTest.java

@Test(groups = { "insert" }, enabled = false)
public void testInsert() {
    Employee emp = employeesMapper.findById(167L);
    Department dept = departmentsMapper.findById(60L);
    Job job = jobsMapper.findById("IT_PROG");

    try {//  w  w  w . j a v a  2s  .co  m
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        java.util.Date start_util_date = formatter.parse("19900101071010");
        java.util.Date end_util_date = new java.util.Date();

        Job_History jh = new Job_History(emp, new Date(start_util_date.getTime()),
                new Date(end_util_date.getTime()), job, dept);

        job_HistoryMapper.insertOne(jh);

        Job_History search = job_HistoryMapper.findByIdRaw(167L, new Date(start_util_date.getTime()));
        List<Job_History> result = job_HistoryMapper.findByRawType(search);

        assertEquals(result.size(), 1);
        assertNotNull(result.get(0));
        assertNotNull(result.get(0).getEmployee());
        assertNotNull(result.get(0).getJob());
        assertNotNull(result.get(0).getDepartment());

    } catch (ParseException ex) {
        assertTrue(false);
    }

}

From source file:com.mapd.bench.BenchmarkCloud.java

void doWork(String[] args, int query) {

    //Grab parameters from args
    // parm0 number of iterations per query
    // parm1 file containing sql queries {contains quoted query, expected result count]
    // parm2 table name
    // parm3 run label
    // parm4 gpu count
    // parm5 optional query and result machine
    // parm6 optional DB URL
    // parm7 optional JDBC Driver class name
    // parm8 optional user
    // parm9 optional passwd
    int iterations = Integer.valueOf(args[0]);
    logger.debug("Iterations per query is " + iterations);

    String queryFile = args[1];//from w ww  .  jav a  2 s.c om
    tableName = args[2];
    label = args[3];
    gpuCount = args[4];

    //int expectedResults = Integer.valueOf(args[2]);
    queryResultMachine = (args.length > 5) ? args[5] : QUERY_RESULT_MACHINE;
    url = (args.length > 6) ? args[6] : DB_URL;
    driver = (args.length > 7) ? args[7] : JDBC_DRIVER;

    iUser = (args.length > 8) ? args[8] : USER;
    iPasswd = (args.length > 9) ? args[9] : PASS;

    //register the driver
    try {
        //Register JDBC driver
        Class.forName(driver);
    } catch (ClassNotFoundException ex) {
        logger.error("Could not load class " + driver + " " + ex.getMessage());
        System.exit(1);
    }

    UUID uuid = UUID.randomUUID();
    rid = uuid.toString();
    java.util.Date date = new java.util.Date();
    Timestamp t = new Timestamp(date.getTime());
    rTimestamp = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(t);

    System.out.println("run id is " + rid + " date is " + rTimestamp);

    // read from query file and execute queries
    String sCurrentLine;
    List<String> resultArray = new ArrayList();
    Map<String, String> queryIDMap = new LinkedHashMap();
    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader(queryFile));

        while ((sCurrentLine = br.readLine()) != null) {

            queryIDMap.put(sCurrentLine, null);
        }
        br.close();

    } catch (FileNotFoundException ex) {
        logger.error("Could not find file " + queryFile + " " + ex.getMessage());
        System.exit(2);
    } catch (IOException ex) {
        logger.error("IO Exeception " + ex.getMessage());
        System.exit(3);
    }

    bencherCon = getConnection("jdbc:mapd:" + queryResultMachine + ":9091:mapd", "mapd", "HyperInteractive");

    getQueries(queryIDMap, bencherCon, tableName);

    runQueries(resultArray, queryIDMap, iterations);

    // if all completed ok store the results
    storeResults();

    // All done dump out results
    System.out.println(header2);
    for (String s : resultArray) {
        System.out.println(s);
    }

}

From source file:org.kuali.kra.award.paymentreports.closeout.AwardCloseoutServiceImpl.java

/**
 * /*from   w ww . jav a  2  s  .  c o  m*/
 * This method updates the due dates for Award Closeout static reports based on allDueDatesAreEqual flag and 
 * by comparing the dateCalculatedUsingFinalInvoiceDue with dateCalculatedUsingFrequency.
 * @param closeoutDueDates
 * @param dateCalculatedUsingFrequency
 * @param allDueDatesAreEqual
 * @param closeoutReportTypeCode
 */
protected void updateCloseoutDueDate(Map<String, Object> closeoutDueDates,
        java.util.Date dateCalculatedUsingFrequency, boolean allDueDatesAreEqual,
        String closeoutReportTypeCode) {
    if (allDueDatesAreEqual) {
        closeoutDueDates.put(closeoutReportTypeCode, new Date(dateCalculatedUsingFrequency.getTime()));
    } else {
        closeoutDueDates.put(closeoutReportTypeCode, MULTIPLE);
    }
}

From source file:com.cemeterylistingsweb.services.impl.SearchSurnameImpl.java

@Override
public List<PublishedDeceasedListing> getAllSurname(String surname, Long subId) {

    List<PublishedDeceasedListing> names = new ArrayList();
    List<PublishedDeceasedListing> all = repo.findAll();
    Subscriber sub = subRepo.findOne(subId);

    //if(surname.isEmpty() || surname.equals("") )
    //      return all;

    for (PublishedDeceasedListing all1 : all) {

        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date parsed = null;
        try {//from  w  ww.ja  va2s.co  m
            parsed = (Date) format.parse(all1.getDateOfDeath());
        } catch (ParseException ex) {
            Logger.getLogger(ViewListingBySubscriberServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        java.sql.Date dod = new java.sql.Date(parsed.getTime());

        if (surname.isEmpty() || surname.equals("") && dod.after(sub.getSubscriptionDate())
                && dod.before(sub.getLastContributionYear()))
            names.add(all1);
        else if (all1.getSurname().equals(surname) && dod.after(sub.getSubscriptionDate())
                && dod.before(sub.getLastContributionYear())) {
            names.add(all1);
        } else if (all1.getSurname().startsWith(surname) && dod.after(sub.getSubscriptionDate())
                && dod.before(sub.getLastContributionYear()))
            names.add(all1);
        else if (all1.getSurname().contains(surname) && dod.after(sub.getSubscriptionDate())
                && dod.before(sub.getLastContributionYear()))
            names.add(all1);
    }

    return names;
}

From source file:su90.mybatisdemo.dao.Job_HistoryMapperTest.java

@Test(groups = { "update" }, dependsOnGroups = { "insert" }, enabled = false)
public void testUpdate() {
    Employee emp = employeesMapper.findById(167L);
    Department dept = departmentsMapper.findById(20L);
    Job job = jobsMapper.findById("HR_REP");

    try {/*from w  ww  . ja v  a  2 s.  c  o  m*/
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        java.util.Date start_util_date = formatter.parse("19900101071010");
        java.util.Date end_util_date = new java.util.Date();

        Job_History search = job_HistoryMapper.findByIdRaw(167L, new Date(start_util_date.getTime()));
        List<Job_History> searchresult = job_HistoryMapper.findByRawType(search);

        Job_History jh = searchresult.get(0);

        jh.setDepartment(dept);
        jh.setJob(job);
        jh.setEnd_date(new Date(end_util_date.getTime()));

        job_HistoryMapper.updateOne(jh);

        Job_History ujh = job_HistoryMapper
                .findById(new Job_History.Key(emp, new Date(start_util_date.getTime())));

        assertEquals(ujh.getDepartment().getId(), new Long(20L));
        assertEquals(ujh.getJob().getId(), "HR_REP");

    } catch (ParseException ex) {
        assertTrue(false);
    }

}

From source file:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override// www .  j ava 2s  .c o m
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(filePath + "temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(req);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:org.jfree.data.jdbc.JDBCCategoryDataset.java

/**
 * Populates the dataset by executing the supplied query against the
 * existing database connection.  If no connection exists then no action
 * is taken./*from w  w  w . jav  a 2 s.c om*/
 * <p>
 * The results from the query are extracted and cached locally, thus
 * applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param con  the connection.
 * @param query  the query.
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;
    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();

        if (columnCount < 2) {
            throw new SQLException("JDBCCategoryDataset.executeQuery() : insufficient columns "
                    + "returned from the database.");
        }

        // Remove any previous old data
        int i = getRowCount();
        while (--i >= 0) {
            removeRow(i);
        }

        while (resultSet.next()) {
            // first column contains the row key...
            Comparable rowKey = resultSet.getString(1);
            for (int column = 2; column <= columnCount; column++) {

                Comparable columnKey = metaData.getColumnName(column);
                int columnType = metaData.getColumnType(column);

                switch (columnType) {
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.INTEGER:
                case Types.BIGINT:
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.DECIMAL:
                case Types.NUMERIC:
                case Types.REAL: {
                    Number value = (Number) resultSet.getObject(column);
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.DATE:
                case Types.TIME:
                case Types.TIMESTAMP: {
                    Date date = (Date) resultSet.getObject(column);
                    Number value = new Long(date.getTime());
                    if (this.transpose) {
                        setValue(value, columnKey, rowKey);
                    } else {
                        setValue(value, rowKey, columnKey);
                    }
                    break;
                }
                case Types.CHAR:
                case Types.VARCHAR:
                case Types.LONGVARCHAR: {
                    String string = (String) resultSet.getObject(column);
                    try {
                        Number value = Double.valueOf(string);
                        if (this.transpose) {
                            setValue(value, columnKey, rowKey);
                        } else {
                            setValue(value, rowKey, columnKey);
                        }
                    } catch (NumberFormatException e) {
                        // suppress (value defaults to null)
                    }
                    break;
                }
                default:
                    // not a value, can't use it (defaults to null)
                    break;
                }
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                // report this?
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                // report this?
            }
        }
    }
}

From source file:org.kuali.kra.committee.bo.CommitteeScheduleTest.java

@Override
protected void boPrerequisite() {
    super.boPrerequisite();
    java.util.Date dt = new java.util.Date(0);
    Time12HrFmt time12HrFmt = new Time12HrFmt("10:30", MERIDIEM.AM);
    dt = DateUtils.round(dt, Calendar.DAY_OF_MONTH);
    dt = DateUtils.addMinutes(dt, time12HrFmt.findMinutes());
    FIELD_TIME_VALUE = new java.sql.Timestamp(dt.getTime());
}

From source file:su90.mybatisdemo.dao.Job_HistoryMapperTest.java

@Test(groups = { "find" })
public void testFindById03() {
    try {// w w  w.  j av a 2s  .c  o  m
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        java.util.Date start_util_date = formatter.parse("20020701");
        Employee thesearchEmp = new Employee();
        thesearchEmp.setId(200L);
        Job_History result = job_HistoryMapper
                .findById(new Job_History.Key(thesearchEmp, new Date(start_util_date.getTime())));
        assertNotNull(result);
    } catch (ParseException ex) {
        assertTrue(false);
    }
}

From source file:org.kuali.kfs.module.ld.batch.service.impl.LaborGLLedgerEntryPoster.java

/**
 * @see org.kuali.kfs.gl.batch.service.PostTransaction#post(org.kuali.kfs.gl.businessobject.Transaction, int, java.util.Date)
 */// w w w.ja  v a 2s. c  o  m
public String post(Transaction transaction, int mode, java.util.Date postDate,
        ReportWriterService posterReportWriterService) {
    String operationType = KFSConstants.OperationType.INSERT;
    LaborGeneralLedgerEntry laborGeneralLedgerEntry = new LaborGeneralLedgerEntry();
    ObjectUtil.buildObject(laborGeneralLedgerEntry, transaction);

    laborGeneralLedgerEntry.setTransactionDate(new Date(postDate.getTime()));

    BalanceType balanceType = getBalanceType(transaction.getFinancialBalanceTypeCode());
    if (balanceType.isFinancialOffsetGenerationIndicator()) {
        laborGeneralLedgerEntry.setTransactionDebitCreditCode(this.getDebitCreditCode(transaction));
    } else {
        laborGeneralLedgerEntry.setTransactionDebitCreditCode(" ");
    }
    laborGeneralLedgerEntry.setTransactionLedgerEntryAmount(this.getTransactionAmount(transaction));

    String encumbranceUpdateCode = this.getEncumbranceUpdateCode(transaction);
    if (StringUtils.isNotEmpty(encumbranceUpdateCode)) {
        laborGeneralLedgerEntry.setTransactionEncumbranceUpdateCode(encumbranceUpdateCode);
    }

    Integer sequenceNumber = laborGeneralLedgerEntryService.getMaxSequenceNumber(laborGeneralLedgerEntry) + 1;
    laborGeneralLedgerEntry.setTransactionLedgerEntrySequenceNumber(sequenceNumber);
    try {
        laborGeneralLedgerEntryService.save(laborGeneralLedgerEntry);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return operationType;
}