List of usage examples for java.sql Timestamp Timestamp
public Timestamp(long time)
From source file:monasca.api.infrastructure.persistence.vertica.StatisticVerticaRepoImpl.java
@Override public List<Statistics> find(String tenantId, String name, Map<String, String> dimensions, DateTime startTime, DateTime endTime, List<String> statisticsCols, int period, String offset, int limit, Boolean mergeMetricsFlag) throws MultipleMetricsException { List<Statistics> statisticsList = new ArrayList<>(); // Sort the column names so that they match the order of the statistics in the results. List<String> statisticsColumns = createColumnsList(statisticsCols); try (Handle h = db.open()) { Map<byte[], Statistics> byteMap = findDefIds(h, tenantId, name, dimensions); if (byteMap.isEmpty()) { return statisticsList; }//from w w w. j ava 2 s .co m if (!Boolean.TRUE.equals(mergeMetricsFlag) && byteMap.keySet().size() > 1) { throw new MultipleMetricsException(name, dimensions); } List<List<Object>> statisticsListList = new ArrayList<>(); String sql = createQuery(byteMap.keySet(), period, startTime, endTime, offset, statisticsCols); logger.debug("vertica sql: {}", sql); Query<Map<String, Object>> query = h.createQuery(sql).bind("start_time", startTime) .bind("end_time", endTime).bind("limit", limit + 1); if (offset != null && !offset.isEmpty()) { logger.debug("binding offset: {}", offset); query.bind("offset", new Timestamp(DateTime.parse(offset).getMillis())); } List<Map<String, Object>> rows = query.list(); for (Map<String, Object> row : rows) { List<Object> statisticsRow = parseRow(row); statisticsListList.add(statisticsRow); } // Just use the first entry in the byteMap to get the def name and dimensions. Statistics statistics = byteMap.entrySet().iterator().next().getValue(); statistics.setColumns(statisticsColumns); if (Boolean.TRUE.equals(mergeMetricsFlag) && byteMap.keySet().size() > 1) { // Wipe out the dimensions. statistics.setDimensions(new HashMap<String, String>()); } statistics.setStatistics(statisticsListList); statisticsList.add(statistics); } return statisticsList; }
From source file:com.dangdang.ddframe.job.event.rdb.JobRdbEventStorage.java
boolean addJobExecutionEvent(final JobExecutionEvent jobExecutionEvent) { boolean result = false; if (null == jobExecutionEvent.getCompleteTime()) { String sql = "INSERT INTO `job_execution_log` (`id`, `job_name`, `hostname`, `sharding_items`, `execution_source`, `is_success`, `start_time`) " + "VALUES (?, ?, ?, ?, ?, ?, ?);"; try (Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setString(1, jobExecutionEvent.getId()); preparedStatement.setString(2, jobExecutionEvent.getJobName()); preparedStatement.setString(3, jobExecutionEvent.getHostname()); preparedStatement.setString(4, jobExecutionEvent.getShardingItems().toString()); preparedStatement.setString(5, jobExecutionEvent.getSource().toString()); preparedStatement.setBoolean(6, jobExecutionEvent.isSuccess()); preparedStatement.setTimestamp(7, new Timestamp(jobExecutionEvent.getStartTime().getTime())); preparedStatement.execute(); result = true;//from w w w . j a va 2 s. c om } catch (final SQLException ex) { // TODO ,??? log.error(ex.getMessage()); } } else { if (jobExecutionEvent.isSuccess()) { String sql = "UPDATE `job_execution_log` SET `is_success` = ?, `complete_time` = ? WHERE id = ?"; try (Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setBoolean(1, jobExecutionEvent.isSuccess()); preparedStatement.setTimestamp(2, new Timestamp(jobExecutionEvent.getCompleteTime().getTime())); preparedStatement.setString(3, jobExecutionEvent.getId()); preparedStatement.execute(); result = true; } catch (final SQLException ex) { // TODO ,??? log.error(ex.getMessage()); } } else { String sql = "UPDATE `job_execution_log` SET `is_success` = ?, `failure_cause` = ? WHERE id = ?"; try (Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setBoolean(1, jobExecutionEvent.isSuccess()); preparedStatement.setString(2, getFailureCause(jobExecutionEvent.getFailureCause())); preparedStatement.setString(3, jobExecutionEvent.getId()); preparedStatement.execute(); result = true; } catch (final SQLException ex) { // TODO ,??? log.error(ex.getMessage()); } } } return result; }
From source file:org.cloudfoundry.identity.uaa.integration.codestore.ExpiringCodeStoreMockMvcTests.java
@Test public void testGenerateCodeWithInvalidScope() throws Exception { Timestamp ts = new Timestamp(System.currentTimeMillis() + 60000); ExpiringCode code = new ExpiringCode(null, ts, "{}"); TestClient testClient = new TestClient(mockMvc); String loginToken = testClient.getClientCredentialsOAuthAccessToken("admin", "adminsecret", ""); String requestBody = new ObjectMapper().writeValueAsString(code); MockHttpServletRequestBuilder post = post("/Codes").header("Authorization", "Bearer " + loginToken) .contentType(APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(requestBody); mockMvc.perform(post).andExpect(status().isForbidden()); }
From source file:cz.zcu.kiv.eegdatabase.webservices.rest.user.UserServiceImpl.java
/** * @{@inheritDoc}/*from w ww . ja va2 s . c om*/ */ @Transactional @Override public PersonData create(String registrationPath, PersonData personData, Locale locale) throws RestServiceException { try { Person person = new Person(); person.setGivenname(personData.getName()); person.setSurname(personData.getSurname()); person.setPassword(personData.getPassword() == null ? ControllerUtils.getRandomPassword() : personData.getPassword()); String plainPassword = person.getPassword(); person.setRegistrationDate(new Timestamp(System.currentTimeMillis())); person.setGender(personData.getGender().charAt(0)); person.setLaterality(personData.getLeftHanded().charAt(0)); person.setDateOfBirth( new Timestamp(ControllerUtils.getDateFormat().parse(personData.getBirthday()).getTime())); person.setPhoneNumber(personData.getPhone()); person.setNote(personData.getNotes()); //dummy default education level List<EducationLevel> def = educationLevelDao.getEducationLevels(DEFAULT_EDUCATION_LEVEL); person.setEducationLevel(def.isEmpty() ? null : def.get(0)); //default role person.setAuthority(Util.ROLE_READER); // security specifics person.setUsername(personData.getEmail()); person.setAuthenticationHash(ControllerUtils.getMD5String(personData.getEmail())); person.setPassword(new BCryptPasswordEncoder().encode(plainPassword)); int pk = personDao.create(person); sendRegistrationConfirmMail(registrationPath, plainPassword, person, locale); personData.setId(pk); return personData; } catch (ParseException e) { log.error(e.getMessage(), e); throw new RestServiceException(e); } catch (MessagingException e) { log.error(e.getMessage(), e); throw new RestServiceException(e); } }
From source file:net.duckling.ddl.service.resource.dao.StarmarkDAOImpl.java
@Override public int batchCreate(final String uid, final int tid, final List<Long> rids) { this.getJdbcTemplate().batchUpdate(SQL_CREATE, new BatchPreparedStatementSetter() { @Override//from w w w . j a v a 2 s . c o m public int getBatchSize() { return (null == rids || rids.isEmpty()) ? 0 : rids.size(); } @Override public void setValues(PreparedStatement ps, int index) throws SQLException { int i = 0; long rid = rids.get(index); ps.setInt(++i, (int) rid); ps.setInt(++i, tid); ps.setString(++i, uid); ps.setTimestamp(++i, new Timestamp((new Date()).getTime())); } }); return 1; }
From source file:org.cloudfoundry.identity.uaa.codestore.CodeStoreEndpointsTests.java
@Test public void testGenerateCodeWithExpiresAtInThePast() throws Exception { String data = "{}"; Timestamp expiresAt = new Timestamp(System.currentTimeMillis() - 60000); ExpiringCode expiringCode = new ExpiringCode(null, expiresAt, data); try {/* w ww . jav a 2 s . c om*/ codeStoreEndpoints.generateCode(expiringCode); fail("expiresAt is in the past, should throw CodeStoreException."); } catch (CodeStoreException e) { assertEquals(e.getStatus(), HttpStatus.BAD_REQUEST); } }
From source file:com.bitranger.parknshop.buyer.controller.MakeOrder.java
@RequestMapping("/submitOrder") public String submitOrder(HttpServletRequest req, Integer psRecipientId) { if (psRecipientId == null) return "redirect:/"; log.debug("Order submitted."); PsCustomer currentCustomer = (PsCustomer) req.getSession().getAttribute("currentCustomer"); if (currentCustomer == null) { log.error("User haven't logged in but submitted an order."); return "redirect:/"; }/*from w w w. j av a2s . com*/ PsRecipient psRecipient = psRecipientDAO.findById(psRecipientId); if (psRecipient == null || (!psRecipient.getPsCustomer().getId().equals(currentCustomer.getId()))) return Utility.error("Recipient ID is invalid."); // FetchOption option = new FetchOption(); // option.ascending(); // option.offset = 0; // option.limit = 100; List<CartCustomerItem> cartItems = psCartCustomerItemDao.findByCustomerId(currentCustomer.getId(), new FetchOption().limit(100).ascending()); Map<PsShop, Set<CartCustomerItem>> shopToPsOrder = new HashMap<PsShop, Set<CartCustomerItem>>(); for (CartCustomerItem item : cartItems) { PsShop currentShop = item.getPsItem().getPsShop(); Set<CartCustomerItem> currentSet = shopToPsOrder.get(currentShop); if (currentSet == null) { currentSet = new HashSet<CartCustomerItem>(); } currentSet.add(item); shopToPsOrder.put(currentShop, currentSet); } for (PsShop psShop : shopToPsOrder.keySet()) { Set<CartCustomerItem> currentShopSet = shopToPsOrder.get(psShop); PsOrder transientOrder = new PsOrder(); transientOrder.setStatus(OrderStatus.UNPAID); transientOrder.setTimeCreated(new Timestamp(System.currentTimeMillis())); transientOrder.setPsCustomer(currentCustomer); transientOrder.setPriceTotal(0.0); transientOrder.setPsRecipient(psRecipient); transientOrder.setPsShop(psShop); log.debug("Ready to save the transient order to the DB"); psOrderDao.save(transientOrder); Set<ROrderItem> orderItems = new HashSet<>(); double priceTotal = 0.0; for (CartCustomerItem item : currentShopSet) { ROrderItem order_item = new ROrderItem( new ROrderItemId(item.getId().getIdItem(), transientOrder.getId()), item.getPsItem(), transientOrder, item.getQuantity(), item.getExtra1(), item.getExtra2()); orderItems.add(order_item); priceTotal += item.getPsItem().getPrice() * item.getQuantity(); } transientOrder.setPriceTotal(priceTotal); transientOrder.setROrderItems(orderItems); psOrderDao.update(transientOrder); log.debug("Save successfully"); } psCartCustomerItemDao.deleteAll(cartItems); return "thankyou"; }
From source file:org.waarp.openr66.protocol.http.rest.handler.HttpRestLogR66Handler.java
@Override public void endParsingRequest(HttpRestHandler handler, RestArgument arguments, RestArgument result, Object body) throws HttpIncorrectRequestException, HttpInvalidAuthenticationException { logger.debug("debug: {} ### {}", arguments, result); if (body != null) { logger.debug("Obj: {}", body); }// w w w .j a va 2 s. c o m handler.setWillClose(false); ServerActions serverHandler = ((HttpRestR66Handler) handler).serverHandler; // now action according to body JsonPacket json = (JsonPacket) body; if (json == null) { result.setDetail("not enough information"); setError(handler, result, HttpResponseStatus.BAD_REQUEST); return; } result.getAnswer().put(AbstractDbData.JSON_MODEL, RESTHANDLERS.Log.name()); try { if (json instanceof LogJsonPacket) {// result.setCommand(ACTIONS_TYPE.GetLog.name()); LogJsonPacket node = (LogJsonPacket) json; boolean purge = node.isPurge(); boolean clean = node.isClean(); Timestamp start = (node.getStart() == null) ? null : new Timestamp(node.getStart().getTime()); Timestamp stop = (node.getStop() == null) ? null : new Timestamp(node.getStop().getTime()); String startid = node.getStartid(); String stopid = node.getStopid(); String rule = node.getRule(); String request = node.getRequest(); boolean pending = node.isStatuspending(); boolean transfer = node.isStatustransfer(); boolean done = node.isStatusdone(); boolean error = node.isStatuserror(); boolean isPurge = purge; String sresult[] = serverHandler.logPurge(purge, clean, start, stop, startid, stopid, rule, request, pending, transfer, done, error, isPurge); LogResponseJsonPacket newjson = new LogResponseJsonPacket(); newjson.fromJson(node); // Now answer newjson.setCommand(node.getRequestUserPacket()); newjson.setFilename(sresult[0]); newjson.setExported(Long.parseLong(sresult[1])); newjson.setPurged(Long.parseLong(sresult[2])); setOk(handler, result, newjson, HttpResponseStatus.OK); } else { logger.info("Validation is ignored: " + json); result.setDetail("Unknown command"); setError(handler, result, json, HttpResponseStatus.PRECONDITION_FAILED); } } catch (OpenR66ProtocolNotAuthenticatedException e) { throw new HttpInvalidAuthenticationException(e); } catch (OpenR66ProtocolBusinessException e) { throw new HttpIncorrectRequestException(e); } }
From source file:edu.ku.brc.af.ui.forms.FormHelper.java
/** * XXX This needs to be moved! This references the specify packge * /*from ww w .j a va2s . co m*/ * Sets the "timestampModified" and the "lastEditedBy" by fields if the exist, if they don't then * then it just ignores the request (no error is thrown). The lastEditedBy use the value of the string * set by the method currentUserEditStr. * @param dataObj the data object to have the fields set * @param doCreatedTime indicates it should set the created time also * @return true if it was able to set the at least one of the fields */ public static boolean updateLastEdittedInfo(final Object dataObj, final boolean doCreatedTime) { log.debug( "updateLastEdittedInfo for [" + (dataObj != null ? dataObj.getClass() : "dataObj was null") + "]"); if (dataObj != null) { if (dataObj instanceof Collection<?>) { boolean retVal = false; for (Object o : (Collection<?>) dataObj) { if (updateLastEdittedInfo(o)) { retVal = true; } } return retVal; } try { DataObjectSettable setter = DataObjectSettableFactory.get(dataObj.getClass().getName(), DATA_OBJ_SETTER); if (setter != null) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); boolean foundOne = false; PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj, "timestampModified"); if (descr != null) { setter.setFieldValue(dataObj, "timestampModified", timestamp); foundOne = true; } if (doCreatedTime) { descr = PropertyUtils.getPropertyDescriptor(dataObj, "timestampCreated"); if (descr != null) { setter.setFieldValue(dataObj, "timestampCreated", timestamp); foundOne = true; } } descr = PropertyUtils.getPropertyDescriptor(dataObj, "modifiedByAgent"); if (descr != null) { setter.setFieldValue(dataObj, "modifiedByAgent", Agent.getUserAgent()); foundOne = true; } return foundOne; } } catch (NoSuchMethodException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class, ex); ex.printStackTrace(); } catch (IllegalAccessException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class, ex); ex.printStackTrace(); } catch (InvocationTargetException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FormHelper.class, ex); ex.printStackTrace(); } } log.debug("updateLastEdittedInfo object is NULL"); return false; }
From source file:com.clustercontrol.monitor.util.MonitorFilterPropertyUtil.java
/** * DTO?????//from w ww . ja v a2s .co m * * @param property * @return */ public static MonitorFilterInfo property2dto(Property property) { MonitorFilterInfo info = new MonitorFilterInfo(); String monitorId = null; // ID String monitorTypeId = null;// ID String description = null; // String facilityId = null; // ID String calendarId = null; // String regUser = null; // ?? Timestamp regFromDate = null; // ?(From) Timestamp regToDate = null; // ?(To) String updateUser = null; // Timestamp updateFromDate = null; // (From) Timestamp updateToDate = null; // (To) Boolean monitorFlg = null; // Boolean collectorFlg = null; // ? String ownerRoleId = null; // ID ArrayList<?> values = null; //ID values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.MONITOR_ID); if (!"".equals(values.get(0))) { monitorId = (String) values.get(0); info.setMonitorId(monitorId); } //ID values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.MONITOR_TYPE_ID); if (!"".equals(values.get(0))) { monitorTypeId = (String) values.get(0); info.setMonitorTypeId(monitorTypeId); } // values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.DESCRIPTION); if (!"".equals(values.get(0))) { description = (String) values.get(0); info.setDescription(description); } //ID values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.FACILITY_ID); if (!"".equals(values.get(0))) { FacilityTreeItem item = (FacilityTreeItem) values.get(0); facilityId = item.getData().getFacilityId(); info.setFacilityId(facilityId); } // values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.CALENDAR_ID); if (!"".equals(values.get(0))) { calendarId = (String) values.get(0); info.setCalendarId(calendarId); } //?? values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.REG_USER); if (!"".equals(values.get(0))) { regUser = (String) values.get(0); info.setRegUser(regUser); } //?(From) values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.REG_FROM_DATE); if (values.get(0) instanceof Date) { regFromDate = new Timestamp(((Date) values.get(0)).getTime()); regFromDate.setNanos(999999999); info.setRegFromDate(regFromDate.getTime()); } //?(To) values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.REG_TO_DATE); if (values.get(0) instanceof Date) { regToDate = new Timestamp(((Date) values.get(0)).getTime()); regToDate.setNanos(999999999); info.setRegToDate(regToDate.getTime()); } // values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.UPDATE_USER); if (!"".equals(values.get(0))) { updateUser = (String) values.get(0); info.setUpdateUser(updateUser); } //(From) values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.UPDATE_FROM_DATE); if (values.get(0) instanceof Date) { updateFromDate = new Timestamp(((Date) values.get(0)).getTime()); updateFromDate.setNanos(999999999); info.setUpdateFromDate(updateFromDate.getTime()); } //(To) values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.UPDATE_TO_DATE); if (values.get(0) instanceof Date) { updateToDate = new Timestamp(((Date) values.get(0)).getTime()); updateToDate.setNanos(999999999); info.setUpdateToDate(updateToDate.getTime()); } // values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.MONITOR_FLG); if (!"".equals(values.get(0))) { if (ValidMessage.STRING_VALID.equals(values.get(0))) { monitorFlg = true; } else { monitorFlg = false; } } info.setMonitorFlg(monitorFlg); // ? values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.COLLECTOR_FLG); if (!"".equals(values.get(0))) { if (ValidMessage.STRING_VALID.equals(values.get(0))) { collectorFlg = true; } else { collectorFlg = false; } } info.setCollectorFlg(collectorFlg); //ID values = PropertyUtil.getPropertyValue(property, MonitorFilterConstant.OWNER_ROLE_ID); if (!"".equals(values.get(0))) { ownerRoleId = (String) values.get(0); info.setOwnerRoleId(ownerRoleId); } return info; }