List of usage examples for java.sql Date Date
public Date(long date)
From source file:com.ewcms.content.resource.service.ResourceService.java
@Override public void publishResourceSuccess(Integer id) { Resource resource = resourceDao.get(id); resource.setStatus(Resource.Status.RELEASED); resource.setPublishTime(new Date(System.currentTimeMillis())); resourceDao.persist(resource);//w w w . ja v a 2s . c o m }
From source file:dialog.DialogFunctionUser.java
private void actionEditUser() { if (!isValidData()) { return;//from w w w. j a v a 2 s . c o m } if (!isValidData()) { return; } String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = mUser.getPassword(); if (tfPassword.getPassword().length == 0) { password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); } int role = cbRole.getSelectedIndex(); if (mAvatar != null) { User objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); if (mControllerUser.editItem(objUser, mRow)) { String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); Path pathOldAvatar = Paths.get(mUser.getAvatar()); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(pathOldAvatar); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } else { User objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mUser.getAvatar()); if (mControllerUser.editItem(objUser, mRow)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } this.dispose(); }
From source file:gov.nih.nci.integration.invoker.CaTissueSpecimenStrategyTest.java
/** * Tests rollbackUpdatedSpecimens using the ServiceInvocationStrategy class for the success scenario * /*from ww w . ja va 2s .com*/ * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void rollbackUpdatedSpecimens() 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 getSpecimenXMLStr(); } }).anyTimes(); final ServiceInvocationResult clientResult = new ServiceInvocationResult(); EasyMock.expect(caTissueSpecimenClient.rollbackUpdatedSpecimens((String) EasyMock.anyObject())) .andReturn(clientResult); EasyMock.replay(caTissueSpecimenClient); final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID, getSpecimenXMLStr(), stTime, caTissueUpdateSpecimenStrategy.getStrategyIdentifier()); final ServiceInvocationResult strategyResult = caTissueUpdateSpecimenStrategy .rollback(serviceInvocationMessage); Assert.assertNotNull(strategyResult); }
From source file:edu.cornell.mannlib.vivo.utilities.rdbmigration.RdbMigrator.java
private void writeMigrationRecord() throws SQLException { String createTable = String.format("CREATE TABLE %s (date DATE)", TABLE_MIGRATED); String deleteOldDates = String.format("DELETE FROM %s", TABLE_MIGRATED); String insertDate = String.format("INSERT INTO %s (date) VALUES (?)", TABLE_MIGRATED); try (Connection conn = getSqlConnection(); Statement stmt = conn.createStatement(); PreparedStatement pstmt = conn.prepareStatement(insertDate)) { if (alreadyMigrated) { stmt.executeUpdate(deleteOldDates); } else {//w w w. jav a2 s. c o m stmt.executeUpdate(createTable); } pstmt.setDate(1, new Date(System.currentTimeMillis())); pstmt.executeUpdate(); } }
From source file:com.sfs.whichdoctor.dao.ExamDAOImpl.java
/** * Save.//ww w . j ava 2 s . com * * @param exam the exam * @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 ExamBean exam, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Check required information within Memo bean is present */ if (exam.getDateSat() == null) { throw new NullPointerException("Exam requires a valid date"); } if (exam.getType() == null) { throw new NullPointerException("Exam type cannot be null"); } if (exam.getType().compareTo("") == 0) { throw new WhichDoctorDaoException("Exam type cannot be an empty string"); } if (exam.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("Exam requires a valid Reference GUID number"); } if (!privileges.getPrivilege(checkUser, "exams", action)) { throw new WhichDoctorDaoException("Insufficient user credentials to create new exam entry"); } int examTypeId = 0, examStatusId = 0, specialtyTypeId = 0, examId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Exam Type", "", exam.getType()); examTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for exam type: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading objecttype for exam type: " + e.getMessage()); } try { ObjectTypeBean object = this.getObjectTypeDAO().load("Exam Status", exam.getType(), exam.getStatusLevel(), exam.getStatus()); examStatusId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for exam status: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading objecttype for exam status: " + e.getMessage()); } try { ObjectTypeBean object = this.getObjectTypeDAO().load("Training Program", exam.getTrainingProgram(), exam.getTrainingOrganisation()); specialtyTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.info("Error loading objecttype for specialty: " + e.getMessage()); } Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); Date dateSat = null; if (exam.getDateSat() != null) { dateSat = new Date(exam.getDateSat().getTime()); } ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(exam.getReferenceGUID()); parameters.add(examTypeId); parameters.add(specialtyTypeId); parameters.add(examStatusId); parameters.add(exam.getLocation()); parameters.add(exam.getAwardedMarks()); parameters.add(exam.getTotalMarks()); parameters.add(dateSat); parameters.add(exam.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(exam.getLogMessage(action)); try { Integer[] result = this.performUpdate("exam", exam.getGUID(), parameters, "Exam", checkUser, action); /* Set the returned guid and id values */ exam.setGUID(result[0]); examId = result[1]; } catch (Exception e) { dataLogger.error("Error processing exam record: " + e.getMessage()); throw new WhichDoctorDaoException("Error processing exam record: " + e.getMessage()); } if (examId > 0) { /* Record created - perform training update */ this.membershipDAO.updateTrainingStatus(exam.getReferenceGUID(), checkUser, privileges); this.trainingStatusDAO.calculate(exam.getReferenceGUID()); } return examId; }
From source file:org.kepler.kar.KARCacheManager.java
/** * Return the contents of the KAR_CONTENTS table that match the given type * or every row if the type given is the empty string. * // ww w .j ava2 s . c om * @param type * @return */ private Vector<KARCacheContent> getKarCacheContents(String whereClause) { Vector<KARCacheContent> contents = new Vector<KARCacheContent>(); String query = "SELECT "; query += KAR_CONTENTS_TABLE_NAME + ".NAME, "; query += KAR_CONTENTS_TABLE_NAME + ".TYPE, "; query += KARS_CACHED_TABLE_NAME + ".FILE, "; query += KARS_CACHED_TABLE_NAME + ".LSID, "; query += KARS_CACHED_TABLE_NAME + ".VERSION, "; query += KARS_CACHED_TABLE_NAME + ".REPONAME, "; query += CacheManager.CACHETABLENAME + ".NAME, "; query += CacheManager.CACHETABLENAME + ".LSID, "; query += CacheManager.CACHETABLENAME + ".DATE, "; query += CacheManager.CACHETABLENAME + ".FILE, "; query += CacheManager.CACHETABLENAME + ".TYPE, "; query += CacheManager.CACHETABLENAME + ".CLASSNAME"; query += " FROM " + KAR_CONTENTS_TABLE_NAME; query += " INNER JOIN " + KARS_CACHED_TABLE_NAME; query += " ON " + KAR_CONTENTS_TABLE_NAME + ".FILE = " + KARS_CACHED_TABLE_NAME + ".FILE"; query += " INNER JOIN " + CacheManager.CACHETABLENAME; query += " ON " + KAR_CONTENTS_TABLE_NAME + ".LSID = " + CacheManager.CACHETABLENAME + ".LSID"; if (!whereClause.trim().equals("")) { query += " " + whereClause; } ResultSet rs; try { if (isDebugging) log.debug(query); rs = _stmt.executeQuery(query); if (rs == null) throw new SQLException("Query Failed: " + query); while (rs.next()) { // Instantiate the KARCacheContent object that we'll return KARCacheContent kcc = new KARCacheContent(); try { kcc.setName(rs.getString(1)); kcc.setType(rs.getString(2)); // Populate the Foreign Key data from the KARS_CACHED table KARCached kc = new KARCached(); File karFile = new File(rs.getString(3)); kc.setFile(karFile); KeplerLSID karLsid = new KeplerLSID(rs.getString(4)); kc.setLsid(karLsid); kc.setVersion(rs.getString(5)); kc.setRepoName(rs.getString(6)); kcc.setKarCached(kc); // Populate the Foreign Key data from the CacheContent table CacheContent cc = new CacheContent(); cc.setName(rs.getString(7)); KeplerLSID ccLsid = new KeplerLSID(rs.getString(8)); cc.setLsid(ccLsid); Date changed = new Date(rs.getLong(9)); cc.setDateChanged(changed); File file = new File(rs.getString(10)); cc.setFile(file); cc.setType(rs.getString(11)); cc.setClassName(rs.getString(12)); kcc.setCacheContent(cc); // Populate the Semantic types kcc.populateSemanticTypes(_stmt); contents.add(kcc); } catch (Exception e) { e.printStackTrace(); } } rs.close(); } catch (SQLException e1) { e1.printStackTrace(); contents = new Vector<KARCacheContent>(); } return contents; }
From source file:de.tuttas.restful.AnwesenheitsManager.java
/** * Heutige Anwesenheit einer Klasse Adresse /api/v1/anwesenheit/{Name der * Klasse}// w w w. j av a 2s . c om * * @param kl Name der Klasse * @return Liste von AnwesenheitsObjekten */ @GET @Path("/{klasse}") public List<AnwesenheitObjekt> getAnwesenheit(@PathParam("klasse") String kl) { em.getEntityManagerFactory().getCache().evictAll(); 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 d1 = new Date(cal.getTimeInMillis()); Date d2 = new Date(cal.getTimeInMillis() + (1000 * 60 * 60 * 24)); Log.d("Webservice Anwesenheit GET from Date=" + d1.toString() + " To " + d2.toString() + " klasse=" + kl); TypedQuery<AnwesenheitEintrag> query = em.createNamedQuery("findAnwesenheitbyKlasse", AnwesenheitEintrag.class); query.setParameter("paramKName", kl); query.setParameter("paramFromDate", d1); query.setParameter("paramToDate", d2); List<AnwesenheitEintrag> anwesenheit = query.getResultList(); Query qb = em.createNamedQuery("findBemerkungbyDate"); qb.setParameter("paramFromDate", d1); qb.setParameter("paramToDate", d2); 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.huison.DriverAssistant_Web.util.LoginHelper.java
public static void register(final BaseActivity activity, final String username, final String phone, final String password, final String tjrphone, final String yzm) { UmengEventSender.sendEvent(activity, UmengEventTypes.register); final ProgressDialog pd = new ProgressDialog(activity); pd.setMessage("..."); pd.setCanceledOnTouchOutside(false); pd.setCancelable(false);//from www . j a v a2 s .c o m pd.show(); /* * Map<String, String> map = new HashMap<String, String>(); * map.put("sessionkey", BaseActivity.getSESSIONKEY()); * map.put("userid", username); map.put("mob", phone); * map.put("passwork", password); map.put("version", * activity.getVersionName()); map.put("imei", * DeviceUniqueIdentifier.getIMEIorMEID(activity)); map.put("imsi", * DeviceUniqueIdentifier.getIMSI(activity)); map.put("mac", * DeviceUniqueIdentifier.getMacAddress(activity)); map.put("channel", * getChannel(activity)); map.put("referee", tjrphone); map.put("Lng", ; * map.put("Lat", HomeActivity.gps_jdHomeActivity.gps_wd)); * map.put("Code", yzm); */ AsyncHttpClient client = activity.getAsyncHttpClient(); RequestParams params = new RequestParams(); /* * params.put("action", REGISTER_ACTION); params.put("xml", * BaseActivity.getXML(map)); */ try { JSONObject p = new JSONObject(); p.put("mobile", phone); p.put("password", password); p.put("method", "register"); p.put("version", activity.getVersionName()); p.put("devicetype", "android"); p.put("channel", getChannel(activity)); p.put("imei", DeviceUniqueIdentifier.getIMEIorMEID(activity)); p.put("imsi", "android" + DeviceUniqueIdentifier.getIMSI(activity)); p.put("lat", Env.latitude); p.put("lng", Env.longitude); p.put("mac", DeviceUniqueIdentifier.getMacAddress(activity)); p.put("referee", tjrphone); p.put("username", username); p.put("code", yzm); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis());// String time = formatter.format(curDate); p.put("time", time); Log.v("JSON", p.toString()); String data = Util.DesJiaMi(p.toString(), "czxms520"); params.put("data", data); } catch (Exception e) { e.printStackTrace(); } client.post(BaseActivity.REQUESTURL, params, new JsonHttpResponseHandler() { @Override public void onDispatchSuccess(int statusCode, Header[] headers, String result) { Log.v("", "1"); pd.dismiss(); try { result = Util.decrypt(result, "czxms520"); Log.v("JSON", result); JSONObject jo = new JSONObject(result); String code = jo.getString("code"); /* * boolean registerFlag = getJSONValueAsString(jo, "code") * .equals("0"); */ String msg = getJSONValueAsString(jo, "message"); if (code.equals("0")) { String data = jo.getString("data"); jo = new JSONObject(data); /* * registerFlag = getJSONValueAsString(jo, "logincode") * .equals("0"); */ // msg = getJSONValueAsString(jo, "loginmessage"); /* * String passwordMD5 = getJSONValueAsString( jo, * "pass"); */ /* * // String breakRuleRemind = * getJSONValueAsString( jo, "wzxx"); // String * changeLicenseRemind = getJSONValueAsString( jo, * "hzxx"); // String examineRemind = * getJSONValueAsString(jo, "nsxx"); */ // vip /* * boolean isVip = getJSONValueAsString(jo, "Vip") * .equals("true"); // String * blackPointUpdateTime = getJSONValueAsString( jo, * "wzhdtime"); // String toolUpdateTime = * getJSONValueAsString( jo, "sygjtime"); // * String favorUpdateTime = getJSONValueAsString( jo, * "yhtime"); */ /* * boolean isVip = getJSONValueAsString(jo, "Vip") * .equals("true"); */ // String loginTime = getJSONValueAsString(jo, "LastLogin"); // String lastLoginTime = getJSONValueAsString(jo, "LastLogin"); // SESSIONKEY /* * String sessionKey = getJSONValueAsString( jo, * "sessionkey"); */ String urlHead = getJSONValueAsString(jo, "PhotoUrl"); String photoUrl = getJSONValueAsString(jo, "PhotoUrl"); String phone = getJSONValueAsString(jo, "Mobile"); Boolean vip = false; if (String.valueOf(jo.getInt("Vip")).equals("1")) { vip = true; } else { vip = false; } Log.v("VIP", String.valueOf(vip)); activity.markLogin(phone, phone, password, true, "", loginTime, lastLoginTime, vip); if (!photoUrl.equals("")) { // String finalHeadUrl = URLDecoder.decode(photoUrl, "utf-8"); BaseActivity.setUserHeadUrl(finalHeadUrl); BaseActivity.setUserHeadDrawable(null); } else { BaseActivity.setUserHeadUrl(""); BaseActivity.setUserHeadDrawable(null); } try { pd.dismiss(); } catch (Exception e) { e.printStackTrace(); } sendMsg(ConfigActivity.thiz, 0); activity.finish(); } else { activity.showMessageBox(msg); } } catch (JSONException e) { e.printStackTrace(); // activity.markLogout(); // sendMsg(activity,1); activity.showMessageBox(activity.getText(R.string.server404)); Log.e("register error", Log.getStackTraceString(e)); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); activity.showMessageBox(""); } } @Override public void onFailureAnyway(int statusCode, Header[] headers, Throwable throwable, BaseBinaryResponse jsonResponse) { Log.v("C", "1"); pd.dismiss(); activity.showMessageBox(activity.getText(R.string.server404)); } @Override public void onSuccessAnyway(int statusCode, Header[] headers, BaseBinaryResponse jsonResponse) { pd.dismiss(); Log.v("A", "1"); } }); Log.v("B", "1"); TimeCounter.countTime(activity, pd); }
From source file:gov.nih.nci.integration.invoker.CaTissueParticipantStrategyTest.java
/** * Tests rollbakUpdateParticipantRegistration using the ServiceInvocationStrategy * /* ww w .j av a2s. c o m*/ * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void rollbakUpdateParticipantRegistration() 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 getSpecimenXMLStr(); } }).anyTimes(); final ServiceInvocationResult clientResult = new ServiceInvocationResult(); EasyMock.expect(caTissueParticipantClient.updateRegistrationParticipant((String) EasyMock.anyObject())) .andReturn(clientResult); EasyMock.replay(caTissueParticipantClient); final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID, getSpecimenXMLStr(), stTime, caTissueUpdateRegistrationStrategy.getStrategyIdentifier()); final ServiceInvocationResult strategyResult = caTissueUpdateRegistrationStrategy .rollback(serviceInvocationMessage); Assert.assertNotNull(strategyResult); }
From source file:GuestBookServlet.java
private void printComments(PrintWriter out, Locale loc) throws IOException { Connection conn = null;/*ww w.j a va 2 s . c om*/ try { DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, loc); ResultSet results; Statement stmt; int rows, count; conn = DriverManager.getConnection(jdbcURL, connectionProperties); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); results = stmt.executeQuery("SELECT NAME, EMAIL, CMT_DATE, " + "COMMENT, COMMENT_ID " + "FROM COMMENT " + "ORDER BY CMT_DATE"); out.println("<dl>"); results.last(); results.next(); rows = results.getRow(); // pick a random row rows = random.nextInt() % rows; if (rows < 4) { // if the random row is less than 4, print the first 4 rows results.afterLast(); } else { // otherwise go to the specified row, print the prior 5 rows results.absolute(rows); } count = 0; // print up to 5 rows going backwards from the randomly // selected row while (results.previous() && (count < 5)) { String name, email, cmt; Date date; count++; name = results.getString(1); if (results.wasNull()) { name = "Unknown User"; } email = results.getString(2); if (results.wasNull()) { email = "user@host"; } date = results.getDate(3); if (results.wasNull()) { date = new Date((new java.util.Date()).getTime()); } cmt = results.getString(4); if (results.wasNull()) { cmt = "No comment."; } out.println("<dt><b>" + name + "</b> (" + email + ") on " + fmt.format(date) + "</dt>"); cmt = noXML(cmt); out.println("<dd> " + cmt + "</dd>"); } out.println("</dl>"); } catch (SQLException e) { out.println("A database error occurred: " + e.getMessage()); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } }