List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:org.sakaiproject.search.component.service.impl.SearchIndexBuilderWorkerImpl.java
public void updateNodeLock(long lifeLeft) throws SQLException { Connection connection = null; String nodeID = getNodeID();/*from w ww. j av a2s . c o m*/ PreparedStatement updateNodeLock = null; PreparedStatement deleteExpiredNodeLock = null; PreparedStatement selectExpiredNodeLock = null; PreparedStatement insertLock = null; ResultSet resultSet = null; String threadID = Thread.currentThread().getName(); boolean savedautocommit = false; Timestamp now = new Timestamp(System.currentTimeMillis()); // a node can expire, after 2 minutes, to indicate to an admin that it // is dead // the admin can then force the Timestamp nodeExpired = new Timestamp(now.getTime() + lifeLeft); try { connection = dataSource.getConnection(); connection.setAutoCommit(false); updateNodeLock = connection.prepareStatement(UPDATE_NODE_LOCK_SQL); deleteExpiredNodeLock = connection.prepareStatement(DELETE_LOCKNODE_SQL); selectExpiredNodeLock = connection.prepareStatement(SELECT_EXPIRED_NODES_SQL); insertLock = connection.prepareStatement(INSERT_LOCK_SQL); int retries = 5; boolean updated = false; while (!updated && retries > 0) { try { try { insertLock.clearParameters(); insertLock.setString(1, "Node:" + nodeID); // id insertLock.setString(2, nodeID); // nodename insertLock.setString(3, NODE_LOCK + nodeID); // lockkey insertLock.setTimestamp(4, nodeExpired); // expires log.debug(threadID + " Doing " + INSERT_LOCK_SQL + ":{" + "Node:" + nodeID + "}{" + nodeID + "}{" + NODE_LOCK + nodeID + "}{" + nodeExpired + "}"); insertLock.executeUpdate(); } catch (SQLException ex) { updateNodeLock.clearParameters(); updateNodeLock.setTimestamp(1, nodeExpired); // expires updateNodeLock.setString(2, nodeID); // nodename updateNodeLock.setString(3, NODE_LOCK + nodeID); // lockkey log.debug(threadID + " Doing " + UPDATE_NODE_LOCK_SQL + ":{" + nodeExpired + "}{" + nodeID + "}{" + NODE_LOCK + nodeID + "}"); if (updateNodeLock.executeUpdate() != 1) { log.warn("Failed to update node heartbeat " + nodeID); } } log.debug(threadID + " Doing Commit "); connection.commit(); updated = true; } catch (SQLException e) { log.warn("Retrying ", e); try { connection.rollback(); } catch (Exception ex) { log.debug(ex); } retries--; try { Thread.sleep(100); } catch (InterruptedException ie) { log.debug(ie); } } } if (!updated) { log.error("Failed to update node lock, will try next time "); } else { log.debug("Updated Node Lock on " + nodeID + " to Expire at" + nodeExpired); } retries = 5; updated = false; while (!updated && retries > 0) { try { selectExpiredNodeLock.clearParameters(); selectExpiredNodeLock.setTimestamp(1, now); log.debug(threadID + " Doing " + SELECT_EXPIRED_NODES_SQL + ":{" + now + "}"); resultSet = selectExpiredNodeLock.executeQuery(); while (resultSet.next()) { String id = resultSet.getString(1); deleteExpiredNodeLock.clearParameters(); deleteExpiredNodeLock.setString(1, id); deleteExpiredNodeLock.execute(); connection.commit(); } log.debug(threadID + " Doing Commit"); connection.commit(); resultSet.close(); updated = true; } catch (SQLException e) { log.info("Retrying Delete Due to " + e.getMessage()); log.debug("Detailed Traceback ", e); try { resultSet.close(); } catch (Exception ex) { log.debug(ex); } try { connection.rollback(); } catch (Exception ex) { log.debug(ex); } retries--; try { Thread.sleep(100); } catch (InterruptedException ie) { log.debug(ie); } } } if (!updated) { log.warn("Failed to clear old nodes, will try next time "); } } catch (Exception ex) { log.error("Failed to register node ", ex); if (connection != null) { connection.rollback(); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.debug(e); } } if (insertLock != null) { try { insertLock.close(); } catch (SQLException e) { log.debug(e); } } if (updateNodeLock != null) { try { updateNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (selectExpiredNodeLock != null) { try { selectExpiredNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (deleteExpiredNodeLock != null) { try { deleteExpiredNodeLock.close(); } catch (SQLException e) { log.debug(e); } } if (connection != null) { try { connection.setAutoCommit(savedautocommit); connection.close(); } catch (SQLException e) { log.debug(e); } connection = null; } } }
From source file:com.chingo247.structureapi.persistence.service.ValidationService.java
private void setRemovedAfter(World world, Timestamp timestamp) { Session session = null;//from w ww . ja v a 2s . co m Transaction tx = null; try { session = HibernateUtil.getSession(); tx = session.beginTransaction(); QStructure qct = QStructure.structure; JPQLQuery query = new HibernateQuery(session); List<Structure> structures = query .from(qct).where( qct.logEntry().autoremoved.eq(Boolean.FALSE) .and(qct.location().worldUUID.eq(world.getUID())).and(qct.logEntry().completedAt .after(timestamp).or(qct.logEntry().removedAt.after(timestamp)))) .list(qct); if (!structures.isEmpty()) { StructureAPI.print( "World " + world + " contains " + structures.size() + " that have an invalid status"); Iterator<Structure> it = structures.iterator(); RegionManager manager = WorldGuardUtil.getRegionManager(Bukkit.getWorld(world.getName())); while (it.hasNext()) { Structure structure = it.next(); if (!manager.hasRegion(structure.getStructureRegion())) { StructureAPI.print("Structure #" + structure.getId() + " was removed after last save"); reclaim(structure); StructureAPI.print("Reclaimed region: " + structure.getStructureRegion()); } // If structure was completed after world save if (timestamp.getTime() < structure.getLog().getCompletedAt().getTime()) { structure.setState(State.STOPPED); structure.getLog().setCompletedAt(null); } else { structure.setState(State.COMPLETE); } structure.getLog().setRemovedAt(null); session.merge(structure); } manager.save(); tx.commit(); } } catch (HibernateException e) { try { if (tx != null) { tx.rollback(); } } catch (HibernateException rbe) { java.util.logging.Logger.getLogger(AbstractService.class.getName()).log(Level.SEVERE, "Couldnt roll back transaction", rbe); } throw e; } catch (StorageException ex) { Logger.getLogger(ValidationService.class.getName()).log(Level.SEVERE, null, ex); } finally { if (session != null) { session.close(); } } }
From source file:org.opentaps.amazon.product.AmazonProductServices.java
/** * Service looks over AmzonProductPrice and collect product prices that haven't been posted yet, * creates XML document for Price Feed and post it to Amazon.com. * @param dctx a <code>DispatchContext</code> value * @param context the service context <code>Map</code> * @return the service response <code>Map</code> *///ww w . j a va 2 s . c o m public static Map<String, Object> publishProductPriceToAmazon(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String prodId = (String) context.get("productId"); try { List<EntityCondition> conditions = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition( "statusId", EntityOperator.IN, Arrays.asList(AmazonConstants.statusProductCreated, AmazonConstants.statusProductChanged, AmazonConstants.statusProductError))); if (UtilValidate.isNotEmpty(prodId)) { conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, prodId)); } TransactionUtil.begin(); EntityListIterator amazonPriceIt = delegator.findListIteratorByCondition("AmazonProductPrice", EntityCondition.makeCondition(conditions, EntityOperator.AND), null, Arrays.asList("productId")); TransactionUtil.commit(); // Prepare Price Feed document long messageId = 1; Map<GenericValue, String> invalidAmazonPrices = new HashMap<GenericValue, String>(); List<GenericValue> validAmazonPrices = new ArrayList<GenericValue>(); Document priceFeed = AmazonConstants.soapClient.createDocumentHeader(AmazonConstants.messageTypePrice); Element root = priceFeed.getDocumentElement(); GenericValue amazonPrice = null; while ((amazonPrice = amazonPriceIt.next()) != null) { String errMessage = null; if (AmazonConstants.productPostRetryThreshold <= amazonPrice.getLong("postFailures").intValue()) { String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostPriceAttemptsOverThreshold", UtilMisc.<String, Object>toMap("productId", amazonPrice.getString("productId"), "threshold", AmazonConstants.productPostRetryThreshold), locale); Debug.logInfo(errorLog, MODULE); continue; } // Ignore products marked deleted if (AmazonUtil.isAmazonProductDeleted(delegator, amazonPrice.getString("productId"))) { String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_IgnoringProductPrice_ProductDeleted", UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale); Debug.logError(errorLog, MODULE); continue; } // check if this product was exported and acknowledged earlier if (delegator.findCountByAnd("AmazonProduct", UtilMisc.toMap("productId", amazonPrice.getString("productId"), "statusId", AmazonConstants.statusProductPosted, "ackStatusId", AmazonConstants.statusProductAckRecv)) != 1) { String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostPriceNonExistentProduct", UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale); Debug.logError(errorLog, MODULE); continue; } /* * Some elements are required. So, we get it first and go to next iteration * if some of these is absent. */ String upc = null; if (AmazonConstants.requireUpcCodes || AmazonConstants.useUPCAsSKU) { // Establish and validate the UPC upc = getProductUPC(delegator, amazonPrice.getString("productId"), locale); if (UtilValidate.isEmpty(upc) && AmazonConstants.requireUpcCodes) { errMessage = AmazonUtil.compoundError(errMessage, UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_MissingCodeUPC", UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale)); } else if (UtilValidate.isNotEmpty(upc) && !UtilProduct.isValidUPC(upc)) { errMessage = AmazonUtil.compoundError(errMessage, UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_InvalidCodeUPC", UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale)); } } // Establish and validate the SKU String sku = getProductSKU(delegator, amazonPrice, upc); if (UtilValidate.isEmpty(sku) && !AmazonConstants.useUPCAsSKU) { errMessage = AmazonUtil .compoundError(errMessage, UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_NoRequiredParameter", UtilMisc.toMap("parameterName", "SKU", "productName", amazonPrice.getString("productId")), locale)); } if (UtilValidate.isNotEmpty(errMessage)) { invalidAmazonPrices.put(amazonPrice, errMessage); continue; } // Standard price - filtered by date BigDecimal standardPrice = null; String standardPriceCurrency = null; // Try to find a price for the Amazon productStoreGroup first EntityCondition cond = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("productId", EntityOperator.EQUALS, amazonPrice.getString("productId")), EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS, AmazonConstants.priceStandard), EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, AmazonConstants.priceProductStoreGroup), EntityUtil.getFilterByDateExpr()); GenericValue standardPriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null, Arrays.asList("lastUpdatedStamp DESC"))); if (UtilValidate.isEmpty(standardPriceVal)) { // If there's no price for the Amazon productStoreGroup, try _NA_ cond = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("productId", EntityOperator.EQUALS, amazonPrice.getString("productId")), EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS, AmazonConstants.priceStandard), EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, "_NA_"), EntityUtil.getFilterByDateExpr()); standardPriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null, Arrays.asList("lastUpdatedStamp DESC"))); } if (UtilValidate.isNotEmpty(standardPriceVal)) { standardPrice = standardPriceVal.getBigDecimal("price").setScale(AmazonConstants.decimals, AmazonConstants.rounding); standardPriceCurrency = standardPriceVal.getString("currencyUomId"); } // Sale price - NOT filtered by date BigDecimal salePrice = null; String salePriceCurrency = null; String saleStartDate = null; String saleEndDate = null; cond = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("productId", EntityOperator.EQUALS, amazonPrice.getString("productId")), EntityCondition.makeCondition("productPriceTypeId", EntityOperator.EQUALS, AmazonConstants.priceSale), EntityCondition.makeCondition("productStoreGroupId", EntityOperator.EQUALS, AmazonConstants.priceProductStoreGroup)); GenericValue salePriceVal = EntityUtil.getFirst(delegator.findByCondition("ProductPrice", cond, null, Arrays.asList("lastUpdatedStamp DESC"))); if (UtilValidate.isNotEmpty(salePriceVal)) { salePrice = salePriceVal.getBigDecimal("price").setScale(AmazonConstants.decimals, AmazonConstants.rounding); salePriceCurrency = salePriceVal.getString("currencyUomId"); Timestamp fromDate = salePriceVal.getTimestamp("fromDate"); Timestamp thruDate = salePriceVal.getTimestamp("thruDate"); Timestamp now = UtilDateTime.nowTimestamp(); if (UtilValidate.isEmpty(thruDate)) { Debug.logInfo( UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostPriceNoSaleEndDate", UtilMisc.toMap("productId", amazonPrice.getString("productId")), locale), MODULE); // Amazon requires an end date for the sale, so add twenty years or so saleEndDate = AmazonUtil .convertTimestampToXSDate(new Timestamp(now.getTime() + 631152000000L)); } else if (thruDate.before(now)) { Debug.logInfo( UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostPriceSalePriceSkipped", UtilMisc.toMap("productId", amazonPrice.getString("productId"), "thruDate", thruDate), locale), MODULE); // The sale is over, so leave out the sale price so that it will be deleted in the Amazon system salePrice = null; } if (UtilValidate.isEmpty(fromDate)) { // Amazon requires a start date for the sale, so use the current time saleStartDate = AmazonUtil.convertTimestampToXSDate(now); } else { // Amazon requires dates to be in the future, so use the current time if the start date for the sale is past saleStartDate = AmazonUtil.convertTimestampToXSDate(fromDate.before(now) ? now : fromDate); } } /* * Create and add required elements and values */ Element message = priceFeed.createElement("Message"); root.appendChild(message); UtilXml.addChildElementValue(message, "MessageID", "" + messageId, priceFeed); Element price = priceFeed.createElement("Price"); message.appendChild(price); UtilXml.addChildElementValue(price, "SKU", sku, priceFeed); // Delist the product (set standard price to zero) if certain conditions are true boolean deListProduct = UtilValidate.isEmpty(standardPrice) || ((UtilValidate.isEmpty(salePriceVal) && AmazonConstants.delistProductIfNoSalePrice)); Element standardPriceElement = UtilXml.addChildElementValue(price, "StandardPrice", deListProduct ? "0.0" : standardPrice.toString(), priceFeed); standardPriceElement.setAttribute("currency", UtilValidate.isNotEmpty(standardPriceCurrency) ? standardPriceCurrency : UtilProperties.getPropertyValue("opentaps.properties", "defaultCurrencyUomId")); if (UtilValidate.isEmpty(standardPrice)) { standardPriceElement.setAttribute("zero", "true"); } if (UtilValidate.isNotEmpty(salePrice)) { Element sale = priceFeed.createElement("Sale"); price.appendChild(sale); UtilXml.addChildElementValue(sale, "StartDate", saleStartDate, priceFeed); UtilXml.addChildElementValue(sale, "EndDate", saleEndDate, priceFeed); Element salePriceElement = UtilXml.addChildElementValue(sale, "SalePrice", salePrice.toString(), priceFeed); salePriceElement.setAttribute("currency", salePriceCurrency); } amazonPrice.set("acknowledgeMessageId", "" + messageId); validAmazonPrices.add(amazonPrice); messageId++; if (messageId % 500 == 0) { Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_Processed_Records_Price", UtilMisc.toMap("count", messageId), locale), MODULE); } } amazonPriceIt.close(); LinkedHashMap<GenericValue, String> emailErrorMessages = new LinkedHashMap<GenericValue, String>(); if (UtilValidate.isEmpty(validAmazonPrices)) { String infoMessage = UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostNoNewPrices", locale); Debug.logInfo(infoMessage, MODULE); } else { boolean success = true; String postErrorMessage = null; long processingDocumentId = -1; try { String xml = UtilXml.writeXmlDocument(priceFeed); Debug.logVerbose(xml, MODULE); Writer writer = new OutputStreamWriter(new FileOutputStream(AmazonConstants.xmlOutputLocation + "AmazonPriceFeed_" + AmazonConstants.xmlOutputDateFormat.format(new Date()) + ".xml"), "UTF-8"); writer.write(xml); writer.close(); processingDocumentId = AmazonConstants.soapClient.postProductPrices(xml); Debug.logInfo(UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_ProcessingDocumentId_Price", UtilMisc.toMap("processingDocumentId", processingDocumentId), locale), MODULE); } catch (RemoteException e) { success = false; postErrorMessage = e.getMessage(); List<String> productIds = EntityUtil.getFieldListFromEntityList(validAmazonPrices, "productId", true); String errorLog = UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_PostPriceError", UtilMisc.toMap("productIds", productIds, "errorMessage", postErrorMessage), locale); Debug.logError(errorLog, MODULE); } // Store operational data of the post attempt for (GenericValue validAmazonPrice : validAmazonPrices) { validAmazonPrice.set("statusId", success ? AmazonConstants.statusProductPosted : AmazonConstants.statusProductError); validAmazonPrice.set("postTimestamp", UtilDateTime.nowTimestamp()); validAmazonPrice.set("postErrorMessage", success ? null : postErrorMessage); if (!success) { validAmazonPrice.set("postFailures", validAmazonPrice.getLong("postFailures") + 1); } validAmazonPrice.set("processingDocumentId", success ? processingDocumentId : null); validAmazonPrice.set("ackStatusId", AmazonConstants.statusProductNotAcked); validAmazonPrice.set("acknowledgeTimestamp", null); validAmazonPrice.set("acknowledgeErrorMessage", null); validAmazonPrice.store(); if (AmazonConstants.sendErrorEmails && !success) { emailErrorMessages.put(validAmazonPrice, postErrorMessage); } } } for (GenericValue invalidAmazonPrice : invalidAmazonPrices.keySet()) { String errorMessage = invalidAmazonPrices.get(invalidAmazonPrice); invalidAmazonPrice.set("statusId", AmazonConstants.statusProductError); invalidAmazonPrice.set("postTimestamp", UtilDateTime.nowTimestamp()); invalidAmazonPrice.set("postErrorMessage", errorMessage); invalidAmazonPrice.set("postFailures", invalidAmazonPrice.getLong("postFailures") + 1); invalidAmazonPrice.set("processingDocumentId", null); invalidAmazonPrice.set("ackStatusId", AmazonConstants.statusProductNotAcked); invalidAmazonPrice.set("acknowledgeTimestamp", null); invalidAmazonPrice.set("acknowledgeErrorMessage", null); invalidAmazonPrice.store(); if (AmazonConstants.sendErrorEmails) { emailErrorMessages.put(invalidAmazonPrice, errorMessage); } } if (AmazonConstants.sendErrorEmails && UtilValidate.isNotEmpty(emailErrorMessages)) { AmazonUtil.sendBulkErrorEmail(dispatcher, userLogin, emailErrorMessages, UtilProperties.getMessage(AmazonConstants.errorResource, "AmazonError_ErrorEmailSubject_PostPrice", AmazonConstants.errorEmailLocale), AmazonConstants.errorEmailScreenUriProducts); } } catch (GenericEntityException gee) { UtilMessage.createAndLogServiceError(gee, locale, MODULE); } catch (IOException ioe) { UtilMessage.createAndLogServiceError(ioe, locale, MODULE); } catch (GenericServiceException gse) { UtilMessage.createAndLogServiceError(gse, locale, MODULE); } return ServiceUtil.returnSuccess(); }
From source file:com.oltpbenchmark.benchmarks.seats.SEATSLoader.java
/** * For the current depart+arrive airport destinations, calculate the estimated * flight time and then add the to the departure time in order to come up with the * expected arrival time./*from w ww . j a v a 2 s .co m*/ * @param depart_airport * @param arrive_airport * @param depart_time * @return */ public Timestamp calculateArrivalTime(String depart_airport, String arrive_airport, Timestamp depart_time) { Integer distance = this.getDistance(depart_airport, arrive_airport); assert (distance != null) : String.format("The calculated distance between '%s' and '%s' is null", depart_airport, arrive_airport); long flight_time = Math.round(distance / SEATSConstants.FLIGHT_TRAVEL_RATE) * 3600000000l; // 60 sec * 60 min * 1,000,000 return (new Timestamp(depart_time.getTime() + flight_time)); }
From source file:com.adito.jdbc.JDBCPolicyDatabase.java
Policy buildPolicy(ResultSet rs) throws Exception { Timestamp cd = rs.getTimestamp("date_created"); Calendar c = Calendar.getInstance(); c.setTimeInMillis(cd == null ? System.currentTimeMillis() : cd.getTime()); Timestamp ad = rs.getTimestamp("date_amended"); Calendar a = Calendar.getInstance(); a.setTimeInMillis(ad == null ? System.currentTimeMillis() : ad.getTime()); return new DefaultPolicy(rs.getInt("id"), rs.getString("policy_name"), rs.getString("policy_description"), rs.getInt("policy_type_id"), c, a, rs.getInt("realm_id")); }
From source file:com.clustercontrol.monitor.util.MonitorFilterPropertyUtil.java
/** * DTO?????/*w w w. j ava 2 s .com*/ * * @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; }
From source file:eu.cloudscale.showcase.generate.GenerateMongo.java
@Override public void populateOrdersAndCC_XACTSTable() { GregorianCalendar cal;/* w ww.j a v a 2 s .co m*/ String[] credit_cards = { "VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS" }; int num_card_types = 5; String[] ship_types = { "AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL" }; int num_ship_types = 6; String[] status_types = { "PROCESSING", "SHIPPED", "PENDING", "DENIED" }; int num_status_types = 4; // Order variables int O_C_ID; java.sql.Timestamp O_DATE; double O_SUB_TOTAL; double O_TAX; double O_TOTAL; String O_SHIP_TYPE; java.sql.Timestamp O_SHIP_DATE; int O_BILL_ADDR_ID, O_SHIP_ADDR_ID; String O_STATUS; String CX_TYPE; int CX_NUM; String CX_NAME; java.sql.Date CX_EXPIRY; String CX_AUTH_ID; int CX_CO_ID; System.out.println("Populating ORDERS, ORDER_LINES, CC_XACTS with " + NUM_ORDERS + " orders"); System.out.print("Complete (in 10,000's): "); for (int i = 1; i <= NUM_ORDERS; i++) { if (i % 10000 == 0) System.out.print(i / 10000 + " "); int num_items = getRandomInt(1, 5); O_C_ID = getRandomInt(1, NUM_CUSTOMERS); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 60)); O_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_SUB_TOTAL = (double) getRandomInt(1000, 999999) / 100; O_TAX = O_SUB_TOTAL * 0.0825; O_TOTAL = O_SUB_TOTAL + O_TAX + 3.00 + num_items; O_SHIP_TYPE = ship_types[getRandomInt(0, num_ship_types - 1)]; cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 7)); O_SHIP_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_BILL_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_SHIP_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_STATUS = status_types[getRandomInt(0, num_status_types - 1)]; Orders order = new Orders(); // Set parameter order.setOId(i); order.setCustomer(customerDao.findById(O_C_ID)); order.setODate(new Date(O_DATE.getTime())); order.setOSubTotal(O_SUB_TOTAL); order.setOTax(O_TAX); order.setOTotal(O_TOTAL); order.setOShipType(O_SHIP_TYPE); order.setOShipDate(O_SHIP_DATE); order.setAddressByOBillAddrId(addressDao.findById(O_BILL_ADDR_ID)); order.setAddressByOShipAddrId(addressDao.findById(O_SHIP_ADDR_ID)); order.setOStatus(O_STATUS); order.setCcXactses(new HashSet<ICcXacts>()); order.setOrderLines(new HashSet<IOrderLine>()); for (int j = 1; j <= num_items; j++) { int OL_ID = j; int OL_O_ID = i; int OL_I_ID = getRandomInt(1, NUM_ITEMS); int OL_QTY = getRandomInt(1, 300); double OL_DISCOUNT = (double) getRandomInt(0, 30) / 100; String OL_COMMENTS = getRandomAString(20, 100); OrderLine orderLine = new OrderLine(); orderLine.setOlId(OL_ID); orderLine.setItem(itemDao.findById(OL_I_ID)); orderLine.setOlQty(OL_QTY); orderLine.setOlDiscount(OL_DISCOUNT); orderLine.setOlComment(OL_COMMENTS); orderLine.setOrders(order); orderLineDao.shrani(orderLine); HashSet<IOrderLine> set = new HashSet<IOrderLine>(); set.add(orderLine); set.addAll(order.getOrderLines()); order.setOrderLines(set); ordersDao.shrani(order); } CX_TYPE = credit_cards[getRandomInt(0, num_card_types - 1)]; CX_NUM = getRandomNString(16); CX_NAME = getRandomAString(14, 30); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, getRandomInt(10, 730)); CX_EXPIRY = new java.sql.Date(cal.getTime().getTime()); CX_AUTH_ID = getRandomAString(15); CX_CO_ID = getRandomInt(1, 92); CcXacts ccXacts = new CcXacts(); ccXacts.setId(i); ccXacts.setCountry(countryDao.findById(CX_CO_ID)); ccXacts.setCxType(CX_TYPE); ccXacts.setCxNum(CX_NUM); ccXacts.setCxName(CX_NAME); ccXacts.setCxExpiry(CX_EXPIRY); ccXacts.setCxAuthId(CX_AUTH_ID); ccXacts.setCxXactAmt(O_TOTAL); ccXacts.setCxXactDate(O_SHIP_DATE); ccXacts.setOrders(order); ccXactsDao.shrani(ccXacts); HashSet<ICcXacts> set = new HashSet<ICcXacts>(); set.add(ccXacts); set.addAll(order.getCcXactses()); order.setCcXactses(set); ordersDao.shrani(order); } System.out.println(""); }
From source file:co.taqat.call.LinphoneActivity.java
public void displayInappNotification(String date) { Timestamp now = new Timestamp(new Date().getTime()); if (LinphonePreferences.instance().getInappPopupTime() != null && Long.parseLong(LinphonePreferences.instance().getInappPopupTime()) > now.getTime()) { return;/*from w ww . j a v a 2 s . c o m*/ } else { long newDate = now.getTime() + getResources().getInteger(R.integer.time_between_inapp_notification); LinphonePreferences.instance().setInappPopupTime(String.valueOf(newDate)); } if (isTrialAccount) { LinphoneService.instance().displayInappNotification( String.format(getString(R.string.inapp_notification_trial_expire), date)); } else { LinphoneService.instance().displayInappNotification( String.format(getString(R.string.inapp_notification_account_expire), date)); } }
From source file:org.apache.phoenix.end2end.DateTimeIT.java
@Test public void testTimestamp() throws Exception { String updateStmt = "upsert into " + tableName + " (" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_TIMESTAMP) " + "VALUES (?, ?, ?)"; // Override value that was set at creation time Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection upsertConn = DriverManager.getConnection(url, props); upsertConn.setAutoCommit(true); // Test auto commit PreparedStatement stmt = upsertConn.prepareStatement(updateStmt); stmt.setString(1, tenantId);//w w w . ja va2 s . c o m stmt.setString(2, ROW4); Timestamp tsValue1 = new Timestamp(5000); byte[] ts1 = PTimestamp.INSTANCE.toBytes(tsValue1); stmt.setTimestamp(3, tsValue1); stmt.execute(); Connection conn1 = DriverManager.getConnection(url, props); TestUtil.analyzeTable(conn1, tableName); conn1.close(); updateStmt = "upsert into " + tableName + " (" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " A_TIMESTAMP," + " A_TIME) " + "VALUES (?, ?, ?, ?)"; stmt = upsertConn.prepareStatement(updateStmt); stmt.setString(1, tenantId); stmt.setString(2, ROW5); Timestamp tsValue2 = new Timestamp(5000); tsValue2.setNanos(200); byte[] ts2 = PTimestamp.INSTANCE.toBytes(tsValue2); stmt.setTimestamp(3, tsValue2); stmt.setTime(4, new Time(tsValue2.getTime())); stmt.execute(); upsertConn.close(); assertTrue(TestUtil.compare(CompareOp.GREATER, new ImmutableBytesWritable(ts2), new ImmutableBytesWritable(ts1))); assertFalse(TestUtil.compare(CompareOp.GREATER, new ImmutableBytesWritable(ts1), new ImmutableBytesWritable(ts1))); String query = "SELECT entity_id, a_timestamp, a_time FROM " + tableName + " WHERE organization_id=? and a_timestamp > ?"; Connection conn = DriverManager.getConnection(url, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setTimestamp(2, new Timestamp(5000)); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(rs.getString(1), ROW5); assertEquals(rs.getTimestamp("A_TIMESTAMP"), tsValue2); assertEquals(rs.getTime("A_TIME"), new Time(tsValue2.getTime())); assertFalse(rs.next()); } finally { conn.close(); } }
From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java
protected void parseField(Object o, MetaField f, ResultSet rs, int j) throws SQLException { switch (f.getType()) { case MetaField.BOOLEAN: { boolean bv = rs.getBoolean(j); if (rs.wasNull()) { f.setBoolean(o, null);/*from ww w . j a va 2s .c om*/ } else { f.setBoolean(o, new Boolean(bv)); } } break; case MetaField.BYTE: { byte bv = rs.getByte(j); if (rs.wasNull()) { f.setByte(o, null); } else { f.setByte(o, new Byte(bv)); } } break; case MetaField.SHORT: { short sv = rs.getShort(j); if (rs.wasNull()) { f.setShort(o, null); } else { f.setShort(o, new Short(sv)); } } break; case MetaField.INT: { int iv = rs.getInt(j); if (rs.wasNull()) { f.setInt(o, null); } else { f.setInt(o, new Integer(iv)); } } break; case MetaField.DATE: { Timestamp tv = rs.getTimestamp(j); if (rs.wasNull()) { f.setDate(o, null); } else { f.setDate(o, new java.util.Date(tv.getTime())); } } break; case MetaField.LONG: { long lv = rs.getLong(j); if (rs.wasNull()) { f.setLong(o, null); } else { f.setLong(o, new Long(lv)); } } break; case MetaField.FLOAT: { float fv = rs.getFloat(j); if (rs.wasNull()) { f.setFloat(o, null); } else { f.setFloat(o, new Float(fv)); } } break; case MetaField.DOUBLE: { double dv = rs.getDouble(j); if (rs.wasNull()) { f.setDouble(o, null); } else { f.setDouble(o, new Double(dv)); } } break; case MetaField.STRING: f.setString(o, rs.getString(j)); break; case MetaField.OBJECT: f.setObject(o, rs.getObject(j)); break; } }