List of usage examples for java.sql Date Date
public Date(long date)
From source file:org.apache.phoenix.pig.util.TypeUtil.java
/** * This method encodes a value with Phoenix data type. It begins with checking whether an object is BINARY and makes * a call to {@link #castBytes(Object, PDataType)} to convert bytes to targetPhoenixType. It returns a {@link RuntimeException} * when object can not be coerced.//from ww w . jav a 2 s . c o m * * @param o * @param targetPhoenixType * @return Object */ public static Object castPigTypeToPhoenix(Object o, byte objectType, PDataType targetPhoenixType) { PDataType inferredPType = getType(o, objectType); if (inferredPType == null) { return null; } if (inferredPType == PVarbinary.INSTANCE) { try { o = castBytes(o, targetPhoenixType); if (targetPhoenixType != PVarbinary.INSTANCE && targetPhoenixType != PBinary.INSTANCE) { inferredPType = getType(o, DataType.findType(o)); } } catch (IOException e) { throw new RuntimeException("Error while casting bytes for object " + o); } } if (inferredPType == PDate.INSTANCE) { int inferredSqlType = targetPhoenixType.getSqlType(); if (inferredSqlType == Types.DATE) { return new Date(((DateTime) o).getMillis()); } if (inferredSqlType == Types.TIME) { return new Time(((DateTime) o).getMillis()); } if (inferredSqlType == Types.TIMESTAMP) { return new Timestamp(((DateTime) o).getMillis()); } } if (targetPhoenixType == inferredPType || inferredPType.isCoercibleTo(targetPhoenixType)) { return inferredPType.toObject(o, targetPhoenixType); } throw new RuntimeException( o.getClass().getName() + " cannot be coerced to " + targetPhoenixType.toString()); }
From source file:edu.cornell.kfs.vnd.businessobject.VendorBatchInsuranceTracking.java
private Date getFormatDate(String stringDate) { SimpleDateFormat format = new SimpleDateFormat("MM.dd.yyyy"); if (stringDate.contains("/")) { format = new SimpleDateFormat("MM/dd/yyyy"); }// w ww. j a v a 2s . co m Date date = null; if (StringUtils.isNotBlank(stringDate)) { try { date = new Date(format.parse(stringDate).getTime()); } catch (Exception e) { } } return date; }
From source file:com.sfs.whichdoctor.dao.MemoDAOImpl.java
/** * Save the updated MemoBean.// w ww . j a va 2 s. c o m * * @param memo the memo * @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 MemoBean memo, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Check required information within Memo bean is present */ if (StringUtils.isBlank(memo.getMessage())) { throw new WhichDoctorDaoException("The memo message cannot be an empty string"); } if (memo.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("The memo requires a valid Reference GUID number"); } if (!privileges.getPrivilege(checkUser, "memos", action)) { throw new WhichDoctorDaoException("Insufficient user credentials to create new memo entry"); } // Get MemoTypeId int memoTypeId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Memo Type", memo.getType(), memo.getObjectType()); memoTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for memo: " + e.getMessage()); throw new WhichDoctorDaoException("The memo requires a valid type: " + e.getMessage()); } int memoId = 0; final Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); Date expiresDate = null; if (memo.getExpires() != null) { expiresDate = new Date(memo.getExpires().getTime()); } final ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(memo.getReferenceGUID()); parameters.add(memoTypeId); parameters.add(memo.getPriority()); parameters.add(memo.getMessage()); parameters.add(expiresDate); parameters.add(memo.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(memo.getLogMessage(action)); try { Integer[] result = this.performUpdate("memo", memo.getGUID(), parameters, "Memo", checkUser, action); /* Set the returned guid and id values */ memo.setGUID(result[0]); memoId = result[1]; } catch (WhichDoctorDaoException wde) { dataLogger.error("Error processing memo record: " + wde.getMessage()); throw new WhichDoctorDaoException("Error processing memo record: " + wde.getMessage()); } return memoId; }
From source file:net.bhira.sample.api.dao.EmployeeDaoImpl.java
/** * @see net.bhira.sample.api.dao.EmployeeDao#save(net.bhira.sample.model.Employee) *//*from w ww. ja v a 2 s . c om*/ @Override public void save(Employee employee) throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException { try { if (employee == null) { throw new InvalidObjectException("Employee object is null."); } employee.initForSave(); employee.validate(); boolean isNew = employee.isNew(); int count = 0; if (isNew) { // for new employee, construct SQL insert statement KeyHolder keyHolder = new GeneratedKeyHolder(); count = jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); pstmt.setLong(1, employee.getCompanyId()); if (employee.getDepartmentId() == 0) { pstmt.setNull(2, java.sql.Types.BIGINT); } else { pstmt.setLong(2, employee.getDepartmentId()); } pstmt.setString(3, employee.getName()); if (employee.getManagerId() == 0) { pstmt.setNull(4, java.sql.Types.BIGINT); } else { pstmt.setLong(4, employee.getManagerId()); } pstmt.setString(5, employee.getSalutation()); pstmt.setString(6, employee.getSex() == null ? null : employee.getSex().toString()); pstmt.setDate(7, employee.getDOB() == null ? null : new Date(employee.getDOB().getTime())); pstmt.setString(8, employee.getTitle()); pstmt.setString(9, employee.getAddress()); pstmt.setTimestamp(10, new Timestamp(employee.getCreated().getTime())); pstmt.setTimestamp(11, new Timestamp(employee.getModified().getTime())); pstmt.setString(12, employee.getCreatedBy()); pstmt.setString(13, employee.getModifiedBy()); return pstmt; } }, keyHolder); // fetch the newly created auto-increment ID employee.setId(keyHolder.getKey().longValue()); LOG.debug("inserted employee, count = {}, id = {}", count, employee.getId()); } else { // for existing employee, construct SQL update statement Long deptId = employee.getDepartmentId() == 0 ? null : employee.getDepartmentId(); Long mgrId = employee.getManagerId() == 0 ? null : employee.getManagerId(); String sex = employee.getSex() == null ? null : employee.getSex().toString(); Date dob = employee.getDOB() == null ? null : new Date(employee.getDOB().getTime()); Object[] args = new Object[] { employee.getCompanyId(), deptId, employee.getName(), mgrId, employee.getSalutation(), sex, dob, employee.getTitle(), employee.getAddress(), employee.getModified(), employee.getModifiedBy(), employee.getId() }; count = jdbcTemplate.update(SQL_UPDATE, args); LOG.debug("updated employee, count = {}, id = {}", count, employee.getId()); } // if insert/update has 0 count value, then rollback if (count <= 0) { throw new ObjectNotFoundException("Employee with ID " + employee.getId() + " was not found."); } // update dependent entries, as needed if (isNew) { // for new model if there is contact info, save it to contact info table and then // add entry in relationship table if (employee.getContactInfo() != null) { contactInfoDao.save(employee.getContactInfo()); Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } else { // for existing model, fetch contact info ID from relationship table List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class, new Object[] { employee.getId() }); Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null; if (employee.getContactInfo() == null) { // clean up old contact info entry, if needed if (cinfoId != null) { jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { employee.getId() }); contactInfoDao.delete(cinfoId); } } else { // insert/update contact info entry if (cinfoId != null) { employee.getContactInfo().setId(cinfoId); contactInfoDao.save(employee.getContactInfo()); } else { contactInfoDao.save(employee.getContactInfo()); Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } } } catch (DataIntegrityViolationException dive) { String msg = dive.getMessage(); if (msg != null) { if (msg.contains("fk_employee_compy")) { throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive); } else if (msg.contains("fk_employee_dept")) { throw new InvalidReferenceException("Invalid reference for attribute 'departmentId'", dive); } else if (msg.contains("fk_employee_mgr")) { throw new InvalidReferenceException("Invalid reference for attribute 'managerId'", dive); } } throw dive; } }
From source file:eu.inmite.apps.smsjizdenka.fragment.TicketsFragment.java
@Override public void onResume() { super.onResume(); // refresh list every full minute mTimer = new Timer(); Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.SECOND, 0); mTimer.scheduleAtFixedRate(new TimerTask() { @Override/* ww w. j a va 2 s. c o m*/ public void run() { c.runOnUiThread(new Runnable() { @Override public void run() { c.getSupportLoaderManager().restartLoader(Constants.LOADER_TICKETS, null, TicketsFragment.this); } }); } }, new Date(calendar.getTimeInMillis()), 1000 * 60); }
From source file:com.sfs.whichdoctor.dao.ExpenseClaimDAOImpl.java
/** * Save the expense claim bean./*from w w w . ja va 2 s . c om*/ * * @param expenseClaim the expense claim * @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 ExpenseClaimBean expenseClaim, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Create expense claim requires all the essential information */ if (expenseClaim.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("Expense claim requires a valid Reference GUID"); } if (!privileges.getPrivilege(checkUser, "expenseclaims", action)) { throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " expense claim"); } int expenseClaimTypeId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Expense Claim", expenseClaim.getExpenseType(), expenseClaim.getExpenseClass()); expenseClaimTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for expense claim: " + e.getMessage()); throw new WhichDoctorDaoException("Expense claim requires a valid expense claim type"); } int expenseClaimId = 0; Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); Date expenseDate = new Date(Calendar.getInstance().getTimeInMillis()); if (expenseClaim.getExpenseDate() != null) { expenseDate = new Date(expenseClaim.getExpenseDate().getTime()); } ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(expenseClaim.getReferenceGUID()); parameters.add(expenseClaimTypeId); parameters.add(expenseClaim.getCurrencyAbbreviation()); parameters.add(expenseDate); parameters.add(expenseClaim.getExchangeRate()); parameters.add(expenseClaim.getDescription()); parameters.add(expenseClaim.getRate()); parameters.add(expenseClaim.getQuantity()); parameters.add(expenseClaim.getGSTRate()); parameters.add(expenseClaim.getValue()); parameters.add(expenseClaim.getNetValue()); parameters.add(expenseClaim.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(expenseClaim.getLogMessage(action)); try { Integer[] result = this.performUpdate("expenseclaim", expenseClaim.getGUID(), parameters, "Expense Claim", checkUser, action); /* Set the returned guid and id values */ expenseClaim.setGUID(result[0]); expenseClaimId = result[1]; } catch (Exception e) { dataLogger.error("Error processing expense claim record: " + e.getMessage()); throw new WhichDoctorDaoException("Error processing expense claim record: " + e.getMessage()); } return expenseClaimId; }
From source file:com.nabla.dc.server.xml.settings.XmlCompany.java
public void load(final Connection conn, final Integer id) throws SQLException { asset_categories = new XmlCompanyAssetCategoryList(conn, id); accounts = new XmlAccountList(conn, id); users = new XmlCompanyUserList(conn, id); // find first financial year + period final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT f.name, p.end_date" + " FROM period_end AS p INNER JOIN financial_year AS f ON p.financial_year_id=f.id" + " WHERE f.company_id=? ORDER BY p.end_date ASC LIMIT 1;", id);/*from w w w . j a v a2 s . com*/ try { final ResultSet rs = stmt.executeQuery(); try { final Calendar dt = new GregorianCalendar(); // i.e. today if (rs.next()) { financial_year = rs.getString(1); dt.setTime(rs.getDate(2)); dt.set(GregorianCalendar.DAY_OF_MONTH, 1); } else { financial_year = new Integer(dt.get(GregorianCalendar.YEAR)).toString(); } start_date = new Date(dt.getTime().getTime()); } finally { rs.close(); } } finally { stmt.close(); } }
From source file:app.order.OrderMetier.java
public void createChecks(int nbrCheque, Bank bank, String checkName, Date dueDate, float deferenceAmount) { Calendar cal = new GregorianCalendar(); cal.setTime(dueDate);//from w ww . ja v a 2 s. c o m //float deferenceAmount = this.order.getTotalAmount() - this.order.getPaidAmount(); float checkAmount = deferenceAmount / nbrCheque; //TODO Formule for (int i = 0; i < nbrCheque; i++) { cal.add(Calendar.MONTH, 1); Check check = (Check) ApplicationContextProvider.getContext().getBean("check"); check.setAvance(false); check.setAmount(checkAmount); check.setBank(bank); check.setDueDate(new Date(cal.getTime().getTime())); check.setName(checkName); //check.setState(CheckState.NONPAYE.toString()); check.setPaymentState(PaymentState.NONPAYE); check.addBill(this.bill); this.bill.addPayment(check); paymentMetier.makePersistent(check); } }
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 va 2 s .c om 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:gov.nih.nci.integration.caaers.CaAERSAdverseEventStrategyTest.java
/** * Tests updateAdverseEvent using the ServiceInvocationStrategy class for the success scenario * //from ww w .ja va2 s . co m * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void updateAdverseEventSuccess() throws IntegrationException, 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 the value to be returned by the method (null for void) return getAEXMLString(); } }).anyTimes(); final CreateProvisionalAdverseEventsResponse caaersresponse = getWSResponse(SUCCESS); EasyMock.expect(wsClient.createProvisionalAdverseEvents((String) EasyMock.anyObject())) .andReturn(caaersresponse); EasyMock.replay(wsClient); }