List of usage examples for java.sql Date Date
public Date(long date)
From source file:org.forumj.dbextreme.db.service.test.user.tests.CreateUserTest.java
private static void prepareUser3() { testUser3.setNick("nick"); testUser3.setPass("pass1"); testUser3.setEmail("mail"); testUser3.setName("name"); testUser3.setFam("fam"); testUser3.setSex("M"); testUser3.setBith(new Date(new java.util.Date().getTime())); testUser3.setPass2("pass2"); testUser3.setShowMail(true);/*www . j ava 2 s . c om*/ testUser3.setShowName(true); testUser3.setCity("city"); testUser3.setShowCity(true); testUser3.setCountry("country"); testUser3.setShowCountry(true); testUser3.setShowSex(true); testUser3.setIcq("icq"); testUser3.setShowIcq(true); testUser3.setShowBithday(true); testUser3.setLanguge(Locale.UA); testUser3.setHideIp(true); testUser3.setView(7); testUser3.setPp(66); testUser3.setPt(77); testUser3.setAvatar("avatar"); testUser3.setShowAvatar(true); testUser3.setAvatarApproved(true); testUser3.setWantSeeAvatars(true); testUser3.setTimeZone(7); testUser3.setFooter("footer"); testUser3.setBan(1); testUser3.setActivateCode(45567678); testUser3.setIsActive(true); }
From source file:com.bmth.MyServlet.RegisterServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Account account = new Account(); // process only if it is multipart content String username = "1"; if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {// w w w . ja v a2 s .co m // Parse the request List<FileItem> multiparts = upload.parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = UPLOAD_DIRECTORY + File.separator + username; File file = new File(fileName); item.write(file); account.setAvatarUrl("http://localhost:8080/Avatar/" + file.getName()); } else { String fieldName = item.getFieldName(); if (fieldName.equals("firstname")) { account.setFullName(item.getString()); } if (fieldName.equals("user_name")) { username = item.getString(); account.setUsername(username); } if (fieldName.equals("nickname")) { account.setNickName(item.getString()); } if (fieldName.equals("user_password")) { account.setPassword(item.getString()); } if (fieldName.equals("user_email")) { account.setEmail(item.getString()); } if (fieldName.equals("sex")) { int gender = item.getString().equals("male") ? 1 : 0; account.setGender(gender); } if (fieldName.equals("date")) { String date = item.getString(); String[] dates = date.split("-"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.parseInt(dates[0])); cal.set(Calendar.MONTH, Integer.parseInt(dates[1])); cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dates[2])); Date birtday = new Date(cal.getTimeInMillis()); account.setBirthDay(birtday); } if (fieldName.equals("address")) { account.setAddress(item.getString()); } } } } catch (Exception e) { e.printStackTrace(); } } account.setPhoneNumber("01698662215"); Register re = new Register(); boolean check = re.AddUser(account); String json; if (check) { Account account1 = re.getAccountbyUsername(username); json = "{\"userId\":" + account1.getUserId() + "}"; } else { json = "{\"userId\": 0}"; } response.getWriter().write(json); }
From source file:org.addsimplicity.anicetus.hibernate.HibernateTest.java
@Test public void testOtherOps() throws Exception { TelemetryContext ctx = (TelemetryContext) m_context.getBean("telemetryContext"); TelemetrySession tsess = ctx.getSession(); tsess.setOperationName("testSimpleTransaction"); SessionFactory fact = (SessionFactory) m_context.getBean("sessionFactory"); m_sess = fact.openSession();/*w ww . ja va2 s .c o m*/ SimpleBean b = new SimpleBean(); b.setText("xyzzy"); Transaction t = m_sess.beginTransaction(); m_sess.save(b); t.commit(); t = m_sess.beginTransaction(); b = (SimpleBean) m_sess.load(SimpleBean.class, Long.valueOf(b.getId())); assertNotNull("Bean found", b); b.setText("abbc"); b.setDate(new Date(System.currentTimeMillis())); m_sess.save(b); t.commit(); t = m_sess.beginTransaction(); m_sess.delete(b); t.commit(); ctx.endSession(); JmsTemplate tmpl = (JmsTemplate) m_context.getBean("consumeTempl"); Object obj = tmpl.receiveAndConvert(); assertNotNull("Object received", obj); assertTrue("Type", obj instanceof TelemetrySession); ExecInfo rsess = (ExecInfo) obj; Collection<GlobalInfo> childs = rsess.getChildren(); assertEquals("Child count", 3, childs.size()); Iterator<GlobalInfo> iter = childs.iterator(); GlobalInfo gi = iter.next(); assertTrue("Type", gi instanceof HibernateTelemetry); HibernateTelemetry ht = (HibernateTelemetry) gi; Collection<HibernateEntity> ents = ht.getHibernateEntities(); assertEquals("Save 1 ents", 1, ents.size()); assertEquals("Save 1 op", HibernateOperation.Create, ents.iterator().next().getOperation()); for (String sql : ht.getSQLStatements()) { System.out.println(sql); } gi = iter.next(); assertTrue("Type", gi instanceof HibernateTelemetry); ht = (HibernateTelemetry) gi; for (String sql : ht.getSQLStatements()) { System.out.println(sql); } ents = ht.getHibernateEntities(); assertEquals("Save 2 ents", 1, ents.size()); assertEquals("Save 2 op", HibernateOperation.Update, ents.iterator().next().getOperation()); gi = iter.next(); assertTrue("Type", gi instanceof HibernateTelemetry); ht = (HibernateTelemetry) gi; for (String sql : ht.getSQLStatements()) { System.out.println(sql); } ents = ht.getHibernateEntities(); assertEquals("Delete ents", 1, ents.size()); assertEquals("Delete op", HibernateOperation.Delete, ents.iterator().next().getOperation()); Collection<String> tabs = ht.getTables(); assertEquals("Tables", 1, tabs.size()); assertEquals("Table Name", "BEANS", tabs.iterator().next()); }
From source file:org.efaps.dataexporter.AbstractDataExporterTestBase.java
/** * Adds the data beans./* w ww. j a va 2s . c o m*/ */ protected void addDataBeans() { final List<SampleBean> beans = new ArrayList<SampleBean>(); beans.add(new SampleBean(new Date(this.dateReference - 2397984), new Integer(1), "Laptop", new Boolean(false), new Integer(1), new Double(799.78))); beans.add(new SampleBean(new Date(this.dateReference - 232042098), new Integer(2), "Mouse", new Boolean(true), new Integer(2), new Double(49.30))); beans.add(new SampleBean(new Date(this.dateReference - 234084277), new Integer(3), "Keyboard", new Boolean(false), new Integer(5), new Double(75))); this.exporter.addBeanRows(beans); }
From source file:org.apigw.monitoring.jms.messagelistener.MonitoringMessageListener.java
private boolean isMessageAlreadyPersisted(String textMessage) throws JsonParseException, IOException { boolean isMessageAlreadyPersisted = false; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> mapObject = mapper.readValue(textMessage, new TypeReference<Map<String, Object>>() { });// w ww . j ava 2 s .c o m if (isResourceEvent(textMessage)) { log.debug("Checking if resource event message has been persisted"); Date timestamp = new Date((Long) mapObject.get("timestamp")); String correlationId = (String) mapObject.get("correlationId"); ResourceEventType eventType = ResourceEventType.valueOf((String) mapObject.get("eventType")); if (correlationId != null && timestamp != null && eventType != null) { List<ResourceEvent> events = resourceEventRepository .findByTimestampAndCorrelationIdAndEventType(timestamp, correlationId, eventType); if (events.size() < 1) { isMessageAlreadyPersisted = false; } else { log.debug("Resource event message was already persisted! Payload was: " + textMessage); isMessageAlreadyPersisted = true; } } } else { log.debug("Checking if auth event message has been persisted"); Date timestamp = new Date((Long) mapObject.get("timestamp")); String client = (String) mapObject.get("client"); AuthEventType eventType = AuthEventType.getEnum((String) mapObject.get("eventType")); if (timestamp != null && eventType != null) { List<AuthEvent> events = authEventRepository.findByTimestampAndClientAndEventType(timestamp, client, eventType); if (events.size() < 1) { isMessageAlreadyPersisted = false; } else { log.debug("Auth event message was already persisted! Payload was: " + textMessage); isMessageAlreadyPersisted = true; } } } return isMessageAlreadyPersisted; }
From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabaseTester.java
License:asdf
@SuppressWarnings("unchecked") @Test//from w w w. j a v a 2 s. co m // FIXME: Split test up. public void testAll() throws Exception { LogbackRecorder lr = LogbackRecorder.startRecorder(); Date beforeTest = new Date(Calendar.getInstance().getTimeInMillis()); assertTrue("The database should be empty to begin with.", cache.isEmpty()); // try handling output from ChecksumJob. File csFile = makeTemporaryChecksumFile1(); cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // try handling output from FilelistJob. File flFile = makeTemporaryFilelistFile(); cache.addFileListInformation(flFile, Replica.getReplicaFromId("TWO")); Date dbDate = cache.getDateOfLastMissingFilesUpdate(Replica.getReplicaFromId("TWO")); Date afterInsert = new Date(Calendar.getInstance().getTimeInMillis()); // Assert that the time of insert is between the start of this test // and now. String stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // Check that getDateOfLastWrongFilesUpdate gives a date between // the start of this test and now. dbDate = cache.getDateOfLastWrongFilesUpdate(Replica.getReplicaFromId("ONE")); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be after " + "the test was begun. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be after '" + DateFormat.getDateInstance().format(beforeTest) + "'."; assertTrue(stepMessage, dbDate.after(beforeTest)); stepMessage = "The last missing file update for replica '" + Replica.getReplicaFromId("ONE") + "' should be before " + "the current time. Thus '" + DateFormat.getDateInstance().format(dbDate) + "' should be before '" + DateFormat.getDateInstance().format(afterInsert) + "'."; assertTrue(stepMessage, dbDate.before(afterInsert)); // retrieve empty file and set all files in replica 'THREE' to missing File fl2File = makeTemporaryEmptyFilelistFile(); cache.addFileListInformation(fl2File, Replica.getReplicaFromId("THREE")); // check that all files are unknown for the uninitialised replica. long files = FileUtils.countLines(csFile); assertEquals("All the files for replica 'THREE' should be missing.", files, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); // check that the getMissingFilesInLastUpdate works appropriately. //List<String> misFiles = toArrayList(cache.getMissingFilesInLastUpdate( List<String> misFiles = IteratorUtils .toList(cache.getMissingFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); List<String> allFilenames = new ArrayList<String>(); for (String entry : FileUtils.readListFromFile(csFile)) { String[] e = entry.split("##"); allFilenames.add(e[0]); } assertEquals("All the files should be missing for replica 'THREE': " + misFiles + " == " + allFilenames, misFiles, allFilenames); // adding the checksum for the other replicas. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("TWO")); // check that when a replica is given wrong checksums it will be // found by the update method. assertEquals("Replica 'THREE' has not been assigned checksums yet." + " Therefore not corrupt files yet!", 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("No files has been assigned to replica 'THREE' yet.", 0, cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); File csFile2 = makeTemporaryChecksumFile2(); cache.addChecksumInformation(csFile2, Replica.getReplicaFromId("THREE")); stepMessage = "All the files in Replica 'THREE' has been assigned checksums, but not checksum update has been run yet. " + "Therefore no corrupt files yet!"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("Entries for replica 'THREE' has should be assigned.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); cache.updateChecksumStatus(); assertEquals("After update all the entries for replica 'THREE', " + "they should all be set to 'CORRUPT'!", FileUtils.countLines(csFile2), cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE"))); assertEquals("All the entries for replica 'THREE' is all corrupt, " + "but they should still be counted.", FileUtils.countLines(csFile2), cache.getNumberOfFiles(Replica.getReplicaFromId("THREE"))); // Check that all files are wrong for replica 'THREE' //List<String> wrongFiles = toArrayList(cache.getWrongFilesInLastUpdate( List<String> wrongFiles = IteratorUtils .toList(cache.getWrongFilesInLastUpdate(Replica.getReplicaFromId("THREE")).iterator()); assertEquals("All the files should be wrong for replica 'THREE': " + wrongFiles + " == " + allFilenames, wrongFiles, allFilenames); // check that a file can become missing, after it was ok, but still be ok! cache.addFileListInformation(flFile, Replica.getReplicaFromId("ONE")); stepMessage = "Replica 'ONE' had the files '" + allFilenames + "' before updating the filelist with '" + FileUtils.readListFromFile(flFile) + "'. Therefore one " + "file should now be missing."; assertEquals(stepMessage, 1, cache.getNumberOfMissingFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); stepMessage = "Replica 'ONE' is missing 1 file, but since the checksum already is set to 'OK', then it is not CORRUPT"; assertEquals(stepMessage, 0, cache.getNumberOfWrongFilesInLastUpdate(Replica.getReplicaFromId("ONE"))); // set replica THREE to having the same checksum as the other two, // and update. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("THREE")); cache.updateChecksumStatus(); // reset the checksums of replica ONE, thus setting the // 'checksum_status' to UNKNOWN. cache.addChecksumInformation(csFile, Replica.getReplicaFromId("ONE")); // Check that replica 'TWO' is found with good file. stepMessage = "Now only replica 'TWO' and 'THREE' both have checksum_status set to OK, and since replica 'TWO' is the only bitarchive, it should found when searching for replica with good file for the file 'TEST1'."; assertEquals(stepMessage, cache.getBitarchiveWithGoodFile("TEST1"), Replica.getReplicaFromId("TWO")); assertEquals("No bitarchive replica should be returned.", null, cache.getBitarchiveWithGoodFile("TEST1", Replica.getReplicaFromId("TWO"))); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST2", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_STARTED); cache.changeStateOfReplicafileinfo("TEST1", Replica.getReplicaFromId("ONE"), ReplicaStoreState.UPLOAD_FAILED); Collection<String> names = cache.retrieveFilenamesForReplicaEntries("TWO", ReplicaStoreState.UPLOAD_STARTED); assertTrue("The list of names should contain TEST1", names.contains("TEST1")); assertTrue("The list of names should contain TEST2", names.contains("TEST2")); cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); try { cache.insertNewFileForUpload("TEST5", "01234567890"); fail("It should not be allowed to reupload a file with another checksum."); } catch (IllegalState e) { // expected assertTrue("It should say, the checksum is wrong, but said: " + e.getMessage(), e.getMessage().contains("The file 'TEST5' with checksum 'asdfasdf0123'" + " has attempted being uploaded with the checksum '" + "01234567890" + "'")); } cache.changeStateOfReplicafileinfo("TEST5", "asdffdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("THREE"), ReplicaStoreState.UPLOAD_COMPLETED); try { cache.insertNewFileForUpload("TEST5", "asdfasdf0123"); fail("It should not be allowed to reupload a file when it has been completed."); } catch (IllegalState e) { // expected assertTrue("It should say, that it has already been completely uploaded, but said: " + e.getMessage(), e.getMessage().contains("The file has already been " + "completely uploaded to the replica: ")); } assertNull("No common checksum should be found for file TEST5", cache.getChecksum("TEST5")); cache.changeStateOfReplicafileinfo("TEST5", "fdsafdas0123", Replica.getReplicaFromId("TWO"), ReplicaStoreState.UPLOAD_COMPLETED); assertEquals("The checksum for file 'TEST5' should be fdsafdas0123", "fdsafdas0123", cache.getChecksum("TEST5")); // check content String content = cache.retrieveAsText(); for (String filename : cache.retrieveAllFilenames()) { assertTrue("The filename '" + filename + "' should be in the content", content.contains(filename)); } for (Replica rep : Replica.getKnown()) { assertEquals("Unexpected filelist status", FileListStatus.NO_FILELIST_STATUS, cache.retrieveFileListStatus("TEST5", rep)); } // check for duplicates cache.addFileListInformation(makeTemporaryDuplicateFilelistFile(), Replica.getReplicaFromId("ONE")); boolean stop = true; if (stop) { return; } lr.assertLogContains("Warning about duplicates should be generated", "There have been found multiple files with the name 'TEST1'"); // cleanup afterwards. cache.cleanup(); lr.stopRecorder(); }
From source file:gov.nih.nci.integration.invoker.CaTissueSpecimenStrategyTest.java
/** * Tests createSpecimens using the ServiceInvocationStrategy class for the failure scenario * /*from w ww . ja v a2 s . c om*/ * @throws IntegrationException - IntegrationException * @throws JAXBException - JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void createSpecimensInvalidAvailableQuantity() 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(); clientResult.setDataChanged(false); clientResult.setOriginalData(getSpecimenXMLStr()); final IntegrationException ie = new IntegrationException(IntegrationError._1085, new Throwable( // NOPMD "Available Quantity cannot be greater than the Initial Quantity"), "Available Quantity cannot be greater than the Initial Quantity"); clientResult.setInvocationException(ie); EasyMock.expect(caTissueSpecimenClient.createSpecimens((String) EasyMock.anyObject())) .andReturn(clientResult); EasyMock.replay(caTissueSpecimenClient); final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID, getSpecimenXMLStr(), stTime, caTissueSpecimenStrategy.getStrategyIdentifier()); final ServiceInvocationResult strategyResult = caTissueSpecimenStrategy.invoke(serviceInvocationMessage); Assert.assertNotNull(strategyResult); }
From source file:com.spotify.heroic.common.DateRange.java
@Override public String toString() { final Date start = new Date(this.start); final Date end = new Date(this.end); return "{" + FORMAT.format(start) + "}-{" + FORMAT.format(end) + "}"; }
From source file:su90.mybatisdemo.dao.EmployeesMapperTest.java
@Test(groups = { "insert" }, enabled = false) // @Test(groups = {"insert"}) public void testInsert() { Employee employee = new Employee("WENTAO", "LI", "wl256@njit.edu", "8625761649", new Date((new java.util.Date()).getTime()), jobsMapper.findById("IT_PROG"), 60000.00, 0.15, employeesMapper.findById(100L), departmentsMapper.findById(60L)); employeesMapper.insertOne(employee); Employee search = new Employee(); search.setEmail("wl256@njit.edu"); List<Employee> result = employeesMapper.findByRawType(search); assertTrue(result.size() > 0);// w ww. j av a2 s. c o m assertEquals(result.get(0).getFname(), "WENTAO"); }
From source file:com.bsg.pcms.sale.company.CompanyContractControllerTest.java
private CompanyContractDTOEx generateContractDto() { CompanyContractDTOEx retVal = new CompanyContractDTOEx(); retVal.setCompany_mgmtno(39);//from w w w . j a va 2 s .com retVal.setLicense_cd("LS001001"); retVal.setSale_price(15000648); retVal.setSale_price_type("0"); retVal.setSale_price_currency("USD"); retVal.setSale_profit_rate(50); retVal.setContract_type("CT002002"); // Contents Group Generate List<String> contentsList = new ArrayList<String>(); contentsList.add("85"); contentsList.add("84"); retVal.setSelectedContentsCd(contentsList); // // Contents Price // List<String> contentsPriceList = new ArrayList<String>(); // contentsPriceList.add("50"); // contentsPriceList.add("100"); // retVal.setSelectedContentsPrice(contentsPriceList); // // // Contents Currency // List<String> selectedContentsCurrency = new ArrayList<String>(); // selectedContentsCurrency.add("USD"); // selectedContentsCurrency.add("KRW"); // retVal.setSelectedContentsCurrency(selectedContentsCurrency); // installments List<String> installments_dt = new ArrayList<String>(); installments_dt.add("2013-07-01"); retVal.setInstallments_dt(installments_dt); List<String> installments_price = new ArrayList<String>(); installments_price.add("123123"); retVal.setInstallments_price(installments_price); retVal.setStr_date(new Date(System.currentTimeMillis())); retVal.setEnd_date(new Date(System.currentTimeMillis())); retVal.setPayments(123123); retVal.setPayments_currency("USD"); retVal.setPayments_type(""); return retVal; }