public static long toLong(Object obj, final long longDefault) { if (obj instanceof Long) { return (Long) obj; } if (obj instanceof Number) { return ((Number) obj).longValue(); } else if (obj instanceof CharSequence) { String str = Str.toString(obj); if (Dates.isJsonDate(str)) { return Dates.fromJsonDate(str).getTime(); } try { return StringScanner.parseLong(str); } catch (Exception ex) { return longDefault; } } else if (obj instanceof Date) { return ((Date) obj).getTime(); } else { return toInt(obj); } }
public JournalEntryWriter entryWriter(long timestamp) throws JournalException { if (!txActive) { beginTx(); } if (checkOrder) { if (timestamp > appendTimestampHi) { switchAppendPartition(timestamp); } if (timestamp < appendTimestampLo) { throw new JournalException( "Cannot insert records out of order. maxHardTimestamp=%d (%s), timestamp=%d (%s): %s", appendTimestampLo, Dates.toString(appendTimestampLo), timestamp, Dates.toString(timestamp), this); } journalEntryWriter.setPartition(appendPartition, timestamp); return journalEntryWriter; } else { journalEntryWriter.setPartition(getAppendPartition(), timestamp); return journalEntryWriter; } }
/** * Add an object to the end of the Journal. * * @param obj the object to add * @throws com.nfsdb.exceptions.JournalException if there is an error */ public void append(T obj) throws JournalException { if (obj == null) { throw new JournalException("Cannot append NULL to %s", this); } if (!txActive) { beginTx(); } if (checkOrder) { long timestamp = getTimestamp(obj); if (timestamp > appendTimestampHi) { switchAppendPartition(timestamp); } if (timestamp < appendTimestampLo) { throw new JournalException( "Cannot insert records out of order. maxHardTimestamp=%d (%s), timestamp=%d (%s): %s", appendTimestampLo, Dates.toString(appendTimestampLo), timestamp, Dates.toString(timestamp), this); } appendPartition.append(obj); appendTimestampLo = timestamp; } else { getAppendPartition().append(obj); } }
public void test_difference_hours() { Date d1 = Dates.newDate(2010, 1, 1, 12, 30, 0); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 0); assertEquals(2, Dates.differenceHours(d1, d2)); Date d3 = Dates.newDate(2010, 1, 1, 12, 30, 0); assertEquals(0, Dates.differenceHours(d1, d3)); }
public void test_difference_days() { Date d1 = Dates.newDate(2010, 1, 1, 12, 30, 0); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 0); assertEquals(0, Dates.differenceDays(d1, d2)); Date d3 = Dates.newDate(2010, 1, 10, 10, 0, 0); assertEquals(8, Dates.differenceDays(d3, d1)); }
public void test_string_conversion() { Date d1 = Dates.newDate(2010, 12, 31, 10, 0, 0); assertEquals("2010-12-31 10:00:00", Dates.toDbString(d1)); assertTrue(Dates.equal(d1, Dates.fromDbString("2010-12-31 10:00:00"))); try { Dates.fromDbString("today"); fail(); } catch (Exception e) { assertEquals("Cannot parse 'today' as date", e.getMessage()); } }
@Test public void Dates() { long current = System.currentTimeMillis(); int dayInMillis = 24 * 60 * 60 * 1000; Date start = new Date(current); ds.delete(ds.createQuery(Dates.class)); Dates d = new Dates(); d.setDate(new Date(current + dayInMillis)); ds.save(d); Date end = new Date(current + 2 * dayInMillis); assertEquals(d, query(dates).where(dates.date.between(start, end)).singleResult()); assertEquals(0, query(dates).where(dates.date.between(new Date(0), start)).count()); }
@Override public void set(String pubDate) { final java.util.Date date = Dates.parseRfc822(pubDate); if (item == null) { feed.setPubDate(date); } else { item.setPubDate(date); } }
public void test_date_compare() { Date d1 = Dates.newDate(2010, 1, 1, 10, 0, 0); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 1); assertTrue(Dates.before(d1, d2)); assertTrue(Dates.beforeOrEqual(d1, d2)); assertTrue(Dates.after(d2, d1)); assertTrue(Dates.afterOrEqual(d2, d1)); assertTrue(Dates.beforeOrEqual(d1, d1)); assertTrue(Dates.afterOrEqual(d1, d1)); assertTrue(Dates.equal(d1, d1)); }
public static Date toEuroDate(String string) { String[] split = StringScanner.splitByChars(string, new char[] {'.', '\\', '/', ':'}); if (split.length == 3) { return Dates.getEuroDate(toInt(split[0]), toInt(split[1]), toInt(split[2])); } else if (split.length >= 6) { return Dates.getEuroDate( toInt(split[0]), toInt(split[1]), toInt(split[2]), toInt(split[3]), toInt(split[4]), toInt(split[5])); } else { die(String.format("Not able to parse %s into a Euro date", string)); return null; } }
// Spent 2 days fighting with dates: I'm giving it up on it! :( public void IGNORED_test_parse_twitter_dates_with_timezone() { String sampleDate = "Sun, 10 Oct 2010 20:56:58 +0002"; try { Date tweetDate = Dates.fromTweeterString(sampleDate); Calendar tweetCalendar = Calendar.getInstance(); tweetCalendar.setTime(tweetDate); assertEquals(2, tweetCalendar.get(Calendar.ZONE_OFFSET)); } catch (RuntimeException e) { e.printStackTrace(); fail("Date Parse Error"); } }
public static Date toDate(Object object) { if (object instanceof Date) { return (Date) object; } else if (object instanceof Value) { return ((Value) object).dateValue(); } else if (object instanceof Calendar) { return ((Calendar) object).getTime(); } else if (object instanceof Long) { return new Date((long) object); } else if (object instanceof String) { String val = (String) object; char[] chars = FastStringUtils.toCharArray(val); if (Dates.isISO8601QuickCheck(chars)) { return Dates.fromISO8601DateLoose(chars); } else { return toDateUS(val); } } return null; }
private void rollback0(long address, boolean writeDiscard) throws JournalException { if (address == -1L) { notifyTxError(); throw new IncompatibleJournalException( "Server txn is not compatible with %s", this.getLocation()); } txLog.read(address, tx); if (tx.address == 0) { throw new JournalException("Invalid transaction address"); } if (writeDiscard) { LOGGER.info( "Journal %s is rolling back to transaction #%d, timestamp %s", metadata.getLocation(), tx.txn, Dates.toString(tx.timestamp)); writeDiscardFile(tx.journalMaxRowID); } // partitions need to be dealt with first to make sure new lag is assigned a correct // partitionIndex rollbackPartitions(tx); Partition<T> lag = getIrregularPartition(); if (tx.lagName != null && tx.lagName.length() > 0 && (lag == null || !tx.lagName.equals(lag.getName()))) { Partition<T> newLag = createTempPartition(tx.lagName); setIrregularPartition(newLag); newLag.applyTx(tx.lagSize, tx.lagIndexPointers); } else if (lag != null && tx.lagName == null) { removeIrregularPartitionInternal(); } else if (lag != null) { lag.truncate(tx.lagSize); } if (tx.symbolTableSizes.length == 0) { for (int i = 0, sz = getSymbolTableCount(); i < sz; i++) { getSymbolTable(i).truncate(); } } else { for (int i = 0, sz = getSymbolTableCount(); i < sz; i++) { getSymbolTable(i).truncate(tx.symbolTableSizes[i]); } } appendTimestampLo = -1; appendTimestampHi = -1; appendPartition = null; txLog.writeTxAddress(tx.address); txActive = false; }
public void postComment(View view) { // Gets the date,user and other things from their classes and changes them to strings and makes // a new comment Dates date = new Dates(); User user = new User(); // Get the other parameters too EditText text = (EditText) findViewById(R.id.comment); String commentText = text.getText().toString(); String currDate = date.getDate(); String theUser = user.getUser(); // Initialize the comments class Comments newComment = new Comments(commentText, currDate, theUser); // How I believe to send the comments through an intent Gson gson = new Gson(); Intent intent = new Intent( this, BrowseComment.class); // Temporary location for now might have to put it in a controller String json = gson.toJson(newComment); intent.putExtra("Class", json); startActivity(intent); }
// El número de factura para una factura nueva private String getCodigo() { // Usamos inicialización vaga if (codigo == null) { // Una consulta JPA para obtener el último número Query query = getManager().createQuery("select max(f.codigo) from Factura f where f.ano = :ano"); // Dates es una utilidad de OpenXava query.setParameter("ano", Dates.getYear(new Date())); Integer lastNumber = (Integer) query.getSingleResult(); if (lastNumber == null) lastNumber = 0; // Añadimos 1 al último número de factura codigo = Integer.toString(lastNumber + 1); } return codigo; }
public void test_parse_twitter_dates() { String sampleDate = "Sun, 10 Oct 2010 20:56:58 +0001"; try { Date tweetDate = Dates.fromTweeterString(sampleDate); Calendar tweetCalendar = Calendar.getInstance(); tweetCalendar.setTime(tweetDate); assertEquals(2010, tweetCalendar.get(Calendar.YEAR)); assertEquals(Calendar.SUNDAY, tweetCalendar.get(Calendar.DAY_OF_WEEK)); assertEquals(Calendar.OCTOBER, tweetCalendar.get(Calendar.MONTH)); assertEquals(20, tweetCalendar.get(Calendar.HOUR_OF_DAY)); assertEquals(56, tweetCalendar.get(Calendar.MINUTE)); } catch (RuntimeException e) { e.printStackTrace(); fail("Date Parse Error"); } }
public Partition<T> getAppendPartition(long timestamp) throws JournalException { int sz = partitions.size(); if (sz > 0) { Partition<T> par = partitions.getQuick(sz - 1); Interval interval = par.getInterval(); if (interval == null || interval.contains(timestamp)) { return par.open().access(); } else if (interval.isBefore(timestamp)) { return createPartition(new Interval(timestamp, getMetadata().getPartitionType()), sz); } else { throw new JournalException("%s cannot be appended to %s", Dates.toString(timestamp), this); } } else { return createPartition(new Interval(timestamp, getMetadata().getPartitionType()), 0); } }
private void writeDiscardFile(long rowid) throws JournalException { if (discardTxtRaf == null) { try { discardTxtRaf = new RandomAccessFile(discardTxt, "rw"); discardTxtRaf.getChannel(); discardSink = new FlexBufferSink( discardTxtRaf.getChannel().position(discardTxtRaf.getChannel().size()), 1024 * 1024); } catch (IOException e) { throw new JournalException(e); } } JournalMetadata m = getMetadata(); int p = Rows.toPartitionIndex(rowid); long row = Rows.toLocalRowID(rowid); long rowCount = 0; try { // partitions for (int n = getPartitionCount() - 1; p < n; p++) { final Partition partition = getPartition(n, true); // partition rows for (long r = row, psz = partition.size(); r < psz; r++) { // partition columns for (int c = 0, cc = m.getColumnCount(); c < cc; c++) { switch (m.getColumnQuick(c).type) { case DATE: Dates.appendDateTime(discardSink, partition.getLong(r, c)); break; case DOUBLE: Numbers.append(discardSink, partition.getDouble(r, c), 12); break; case FLOAT: Numbers.append(discardSink, partition.getFloat(r, c), 4); break; case INT: Numbers.append(discardSink, partition.getInt(r, c)); break; case STRING: partition.getStr(r, c, discardSink); break; case SYMBOL: discardSink.put(partition.getSym(r, c)); break; case SHORT: Numbers.append(discardSink, partition.getShort(r, c)); break; case LONG: Numbers.append(discardSink, partition.getLong(r, c)); break; case BYTE: Numbers.append(discardSink, partition.getByte(r, c)); break; case BOOLEAN: discardSink.put(partition.getBool(r, c) ? "true" : "false"); break; } if (((++rowCount) & 7) == 0) { discardSink.flush(); } } } } } finally { discardSink.flush(); } }
// Should reflect java.util.Comparator specification public void test_should_returns_a_negative_integer_if_the_first_argument_is_less_than_the_second() { Date d1 = Dates.newDate(2010, 1, 1, 10, 0, 0); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 1); assertTrue(Dates.differenceSeconds(d1, d2) < 0); }
public void test_smart_date_differences() { Date d1 = Dates.newDate(2010, 1, 1, 10, 30, 0); Date d2 = Dates.newDate(2010, 1, 3, 11, 30, 0); assertEquals("2 days from now", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 9, 29, 58); assertEquals("one hour ago", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 12, 30, 5); assertEquals("2 hours from now", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 10, 0, 0); assertEquals("30 minutes ago", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 10, 29, 0); assertEquals("one minute ago", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 10, 30, 0); assertEquals("now", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 10, 29, 1); assertEquals("now", Dates.differenceSmart(d1, d2)); d2 = Dates.newDate(2010, 1, 1, 10, 30, 5); assertEquals("now", Dates.differenceSmart(d1, d2)); }
public Object executeTask(Object object) throws Exception { List result; try { Map incomingRequest = (Map) object; DBSession dbs = (DBSession) incomingRequest.get("dbsession"); String o = (String) incomingRequest.get("organizationId"); String userId = (String) incomingRequest.get("userId"); String userDateFormat = (String) incomingRequest.get("userDateFormat"); BrowseObject b = (BrowseObject) incomingRequest.get("browseObject"); List groupFilters = b.getGroupFilters(); List groupFilterOptions = new ArrayList(); List commodities = new ArrayList(); // boolean unspscCommodities = PropertiesManager.getInstance(o).getProperty("MISC", // "CommodityType", "").equalsIgnoreCase("UNSPSC"); boolean unspscCommodities = false; boolean commoditySet = false; PropertiesManager propertiesManager = PropertiesManager.getInstance(o); if (Utility.isEmpty(userDateFormat)) { userDateFormat = propertiesManager.getProperty("MISC", "DateFormat", "MM-dd-yyyy"); } for (int ix = 0; ix < groupFilters.size(); ix++) { BrowseGroupFilter gf = (BrowseGroupFilter) groupFilters.get(ix); StringBuffer query = new StringBuffer(); StringBuffer queryFilter = new StringBuffer(); if (!Utility.isEmpty(gf.getType()) && gf.getType().equals("CostRange")) { incomingRequest.put("CostRange_itemType", incomingRequest.get("as_item_type")); } List dateArguments = new ArrayList(); if (Utility.isEmpty(gf.getType()) || !gf.getType().equals("Keywords")) { query.append(gf.getSqlSelect() + " from " + gf.getSqlFrom() + " where 1 = 1"); if (Utility.ckNull(gf.getSqlWhere()).length() > 0) { query.append(" and ( " + gf.getSqlWhere() + ")"); } if (Utility.ckNull(b.getSqlWhere()).length() > 0) { String sqlWhere = b.getSqlWhere(); sqlWhere = sqlWhere.replaceAll(":as_userid", "'" + userId + "'"); if (sqlWhere.indexOf(":as_today") > 0) { dateArguments.add( Dates.getDate( Dates.today(userDateFormat, (String) incomingRequest.get("userTimeZone")))); } sqlWhere = sqlWhere.replaceAll(":as_today", "?"); query.append(" and ( " + sqlWhere + ")"); } List filters = b.getBrowseFilters(); if (filters != null) { for (int i = 0; i < filters.size(); i++) { BrowseFilter filter = (BrowseFilter) filters.get(i); String key = filter.getColumnName(); if (!b.validateColumn(key)) { // skip this filter continue; } String value = encoder.encodeForSQL(new OracleCodec(), filter.getValue()); String operator = filter.getOperator(); String logicalOperator = filter.getLogicalOperator(); if (!BrowseValidationUtility.permissibleOperators.contains(operator)) { operator = "="; } if (!BrowseValidationUtility.permissibleLogicalOperators.contains(logicalOperator)) { logicalOperator = "AND"; } String type = filter.getType(); if (!Utility.isEmpty(value)) { if (Utility.isEmpty(operator)) { operator = "="; } if (Utility.isEmpty(logicalOperator)) { logicalOperator = "AND"; } if (Utility.isEmpty(type)) { type = "STRING"; } if (queryFilter.length() > 0) { queryFilter.append(" " + logicalOperator + " "); } if (type.equalsIgnoreCase("DATE")) { dateArguments.add(Dates.getDate(userDateFormat, value)); queryFilter.append(" " + key + " " + operator + " ?"); } else if (operator.equalsIgnoreCase("LIKE")) { queryFilter.append(" UPPER(" + key + ") " + operator + " '" + value + "'"); } else { queryFilter.append(" " + key + " " + operator + " '" + value + "'"); } if (key.indexOf(".commodity") > 0) { if (!Utility.isEmpty(value)) { commoditySet = true; if (value.indexOf("%") > 0) { String commodity = "00000000"; for (int iv = 0; iv < value.length(); iv++) { char temp = value.charAt(iv); if (temp != '%') { if (iv == 0) { commodity = temp + commodity.substring(iv + 1); } else if (commodity.length() >= (iv + 1)) { commodity = commodity.substring(0, iv) + temp + commodity.substring(iv + 1); } else { commodity = commodity.substring(0, iv) + temp; } } } if (!commodities.contains(commodity)) { commodities.add(commodity); } } } } } } } if (queryFilter.length() > 0) { query.append("AND (" + queryFilter + " )"); } if (gf.getType().equalsIgnoreCase("Commodity") && unspscCommodities) { String originalQueryString = query.toString(); List commodityList = null; CommodityGetUNSPSCWhereClause commodityWhere = new CommodityGetUNSPSCWhereClause(); int attempts = 0; while ((commodityList == null || commodityList.size() == 0) && attempts <= 3) { query = new StringBuffer(originalQueryString); String commodityArray[] = new String[commodities.size()]; commodities.toArray(commodityArray); incomingRequest.put("Commodity_commodity", commodityArray); incomingRequest.put("retrieveAllCodes", "N"); if (attempts > 0) { incomingRequest.put("retrieveAllFamilies", "Y"); if (attempts > 1) { incomingRequest.put("retrieveAllGroups", "Y"); if (attempts > 2) { incomingRequest.put("retrieveAllCommodities", "Y"); } } } String unspscWhere = (String) commodityWhere.executeTask(incomingRequest); if (!Utility.isEmpty(unspscWhere)) { query.append(" AND (" + unspscWhere + ")"); } if (!Utility.isEmpty(gf.getSqlGroupBy())) { query.append(" group by " + gf.getSqlGroupBy()); } if (!Utility.isEmpty(gf.getSqlOrderBy())) { query.append(" order by " + gf.getSqlOrderBy()); } Log.debug(this, "group filter query: " + query.toString()); Object arguments[] = new Object[dateArguments.size()]; for (int i = 0; i < dateArguments.size(); i++) { arguments[i] = dateArguments.get(i); } commodityList = dbs.query(query.toString(), arguments); attempts++; } gf.setSelectionValues(commodityList); } else { if (!Utility.isEmpty(gf.getSqlGroupBy())) { query.append(" group by " + gf.getSqlGroupBy()); } if (!Utility.isEmpty(gf.getSqlOrderBy())) { query.append(" order by " + gf.getSqlOrderBy()); } Log.debug(this, "group filter query: " + query.toString()); Object arguments[] = new Object[dateArguments.size()]; for (int i = 0; i < dateArguments.size(); i++) { arguments[i] = dateArguments.get(i); } List list = dbs.query(query.toString(), arguments); gf.setSelectionValues(list); } } } result = groupFilters; this.setStatus(dbs.getStatus()); } catch (Exception e) { e.printStackTrace(); throw e; } return result; }
public Object executeTask(Object object) throws Exception { Map incomingRequest = (Map) object; Object result = null; try { InvStage invStage = (InvStage) incomingRequest.get("invStage"); if (invStage == null) { invStage = new InvStage(); } if (incomingRequest.containsKey("InvStage_stageId")) { String stageId = (String) incomingRequest.get("InvStage_stageId"); invStage.setStageId(stageId); } if (incomingRequest.containsKey("InvStage_description")) { String description = (String) incomingRequest.get("InvStage_description"); invStage.setDescription(description); } if (incomingRequest.containsKey("InvStage_respons")) { String respons = (String) incomingRequest.get("InvStage_respons"); invStage.setRespons(respons); } if (incomingRequest.containsKey("InvStage_notes")) { String notes = (String) incomingRequest.get("InvStage_notes"); invStage.setNotes(notes); } if (incomingRequest.containsKey("InvStage_workCenterId")) { String workCenterId = (String) incomingRequest.get("InvStage_workCenterId"); invStage.setWorkCenterId(workCenterId); } if (incomingRequest.containsKey("InvStage_utilization")) { String utilizationString = (String) incomingRequest.get("InvStage_utilization"); if (Utility.isEmpty(utilizationString)) { utilizationString = "0"; } BigDecimal utilization = new BigDecimal(utilizationString); invStage.setUtilization(utilization); } if (incomingRequest.containsKey("InvStage_qtyDays")) { String qtyDaysString = (String) incomingRequest.get("InvStage_qtyDays"); if (Utility.isEmpty(qtyDaysString)) { qtyDaysString = "0"; } BigDecimal qtyDays = new BigDecimal(qtyDaysString); invStage.setQtyDays(qtyDays); } if (incomingRequest.containsKey("InvStage_setupHours")) { String setupHoursString = (String) incomingRequest.get("InvStage_setupHours"); if (Utility.isEmpty(setupHoursString)) { setupHoursString = "0"; } BigDecimal setupHours = new BigDecimal(setupHoursString); invStage.setSetupHours(setupHours); } if (incomingRequest.containsKey("InvStage_partsHour")) { String partsHourString = (String) incomingRequest.get("InvStage_partsHour"); if (Utility.isEmpty(partsHourString)) { partsHourString = "0"; } BigDecimal partsHour = new BigDecimal(partsHourString); invStage.setPartsHour(partsHour); } if (incomingRequest.containsKey("InvStage_timePart")) { String timePartString = (String) incomingRequest.get("InvStage_timePart"); if (Utility.isEmpty(timePartString)) { timePartString = "0"; } BigDecimal timePart = new BigDecimal(timePartString); invStage.setTimePart(timePart); } if (incomingRequest.containsKey("InvStage_vendorName")) { String vendorName = (String) incomingRequest.get("InvStage_vendorName"); invStage.setVendorName(vendorName); } if (incomingRequest.containsKey("InvStage_leadTime")) { String leadTimeString = (String) incomingRequest.get("InvStage_leadTime"); if (Utility.isEmpty(leadTimeString)) { leadTimeString = "0"; } BigDecimal leadTime = new BigDecimal(leadTimeString); invStage.setLeadTime(leadTime); } if (incomingRequest.containsKey("InvStage_outside")) { String outside = (String) incomingRequest.get("InvStage_outside"); invStage.setOutside(outside); } if (incomingRequest.containsKey("InvStage_descriptor")) { String descriptor = (String) incomingRequest.get("InvStage_descriptor"); invStage.setDescriptor(descriptor); } if (incomingRequest.containsKey("InvStage_machineId")) { String machineId = (String) incomingRequest.get("InvStage_machineId"); invStage.setMachineId(machineId); } if (incomingRequest.containsKey("InvStage_backflush")) { String backflush = (String) incomingRequest.get("InvStage_backflush"); invStage.setBackflush(backflush); } if (incomingRequest.containsKey("InvStage_persons")) { String personsString = (String) incomingRequest.get("InvStage_persons"); if (Utility.isEmpty(personsString)) { personsString = "0"; } BigDecimal persons = new BigDecimal(personsString); invStage.setPersons(persons); } if (incomingRequest.containsKey("InvStage_ccost")) { String ccostString = (String) incomingRequest.get("InvStage_ccost"); if (Utility.isEmpty(ccostString)) { ccostString = "0"; } BigDecimal ccost = new BigDecimal(ccostString); invStage.setCcost(ccost); } if (incomingRequest.containsKey("InvStage_unitOfMeasure")) { String unitOfMeasure = (String) incomingRequest.get("InvStage_unitOfMeasure"); invStage.setUnitOfMeasure(unitOfMeasure); } if (incomingRequest.containsKey("InvStage_dateEntered")) { String dateEnteredString = (String) incomingRequest.get("InvStage_dateEntered"); Date dateEntered = Dates.getDate(dateEnteredString); invStage.setDateEntered(dateEntered); } if (incomingRequest.containsKey("InvStage_dateExpires")) { String dateExpiresString = (String) incomingRequest.get("InvStage_dateExpires"); Date dateExpires = Dates.getDate(dateExpiresString); invStage.setDateExpires(dateExpires); } if (incomingRequest.containsKey("InvStage_owner")) { String owner = (String) incomingRequest.get("InvStage_owner"); invStage.setOwner(owner); } if (incomingRequest.containsKey("InvStage_status")) { String status = (String) incomingRequest.get("InvStage_status"); invStage.setStatus(status); } result = invStage; this.status = Status.SUCCEEDED; } catch (Exception e) { this.status = Status.FAILED; throw e; } return result; }
public Object executeTask(Object object) throws Exception { Map incomingRequest = (Map) object; Object result = null; try { BomMethod bomMethod = (BomMethod) incomingRequest.get("bomMethod"); if (bomMethod == null) { bomMethod = new BomMethod(); } if (incomingRequest.containsKey("BomMethod_icMethod")) { String icMethodString = (String) incomingRequest.get("BomMethod_icMethod"); if (Utility.isEmpty(icMethodString)) { icMethodString = "0"; } BigDecimal icMethod = new BigDecimal(icMethodString); bomMethod.setIcMethod(icMethod); } if (incomingRequest.containsKey("BomMethod_parentItem")) { String parentItem = (String) incomingRequest.get("BomMethod_parentItem"); bomMethod.setParentItem(parentItem); } if (incomingRequest.containsKey("BomMethod_componentItem")) { String componentItem = (String) incomingRequest.get("BomMethod_componentItem"); bomMethod.setComponentItem(componentItem); } if (incomingRequest.containsKey("BomMethod_methodId")) { String methodId = (String) incomingRequest.get("BomMethod_methodId"); bomMethod.setMethodId(methodId); } if (incomingRequest.containsKey("BomMethod_batchSize")) { String batchSizeString = (String) incomingRequest.get("BomMethod_batchSize"); if (Utility.isEmpty(batchSizeString)) { batchSizeString = "0"; } BigDecimal batchSize = new BigDecimal(batchSizeString); bomMethod.setBatchSize(batchSize); } if (incomingRequest.containsKey("BomMethod_unitOfMeasure")) { String unitOfMeasure = (String) incomingRequest.get("BomMethod_unitOfMeasure"); bomMethod.setUnitOfMeasure(unitOfMeasure); } if (incomingRequest.containsKey("BomMethod_description")) { String description = (String) incomingRequest.get("BomMethod_description"); bomMethod.setDescription(description); } if (incomingRequest.containsKey("BomMethod_notes")) { String notes = (String) incomingRequest.get("BomMethod_notes"); bomMethod.setNotes(notes); } if (incomingRequest.containsKey("BomMethod_dateEntered")) { String dateEnteredString = (String) incomingRequest.get("BomMethod_dateEntered"); Date dateEntered = Dates.getDate(dateEnteredString); bomMethod.setDateEntered(dateEntered); } if (incomingRequest.containsKey("BomMethod_owner")) { String owner = (String) incomingRequest.get("BomMethod_owner"); bomMethod.setOwner(owner); } result = bomMethod; this.status = Status.SUCCEEDED; } catch (Exception e) { this.status = Status.FAILED; throw e; } return result; }
@Test public void should_not_be_null() { Date lastDayOfMonth = Dates.findLastDayOfMonth(); assertNotNull(lastDayOfMonth); }
// Should reflect java.util.Comparator specification public void test_should_returns_a_positive_integer_as_the_first_argument_is_greater_than_the_second() { Date d1 = Dates.newDate(2010, 1, 1, 10, 0, 1); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 0); assertTrue(Dates.differenceSeconds(d1, d2) > 0); }
/* (non-Javadoc) * @see com.tsagate.puridiom.process.ITask#executeTask(java.lang.Object) */ public Object executeTask(Object object) throws Exception { Map incomingRequest = (Map) object; Object result = null; try { String organizationId = (String) incomingRequest.get("organizationId"); String userDateFormat = (String) incomingRequest.get("userDateFormat"); PropertiesManager propertiesManager = PropertiesManager.getInstance(organizationId); CatalogSecurity catalogSecurity = (CatalogSecurity) incomingRequest.get("catalogSecurity"); String isCatalog = HiltonUtility.ckNull((String) incomingRequest.get("isCatalog")); String catalogId = (String) catalogSecurity.getCatalogId(); String accesType = (String) catalogSecurity.getAccessType(); String accessId = (String) catalogSecurity.getAccessId(); if (HiltonUtility.isEmpty(userDateFormat)) { userDateFormat = propertiesManager.getProperty("MISC", "DateFormat", "MM-dd-yyyy"); } String today = Dates.today(userDateFormat, (String) incomingRequest.get("userTimeZone")); if (isCatalog.equalsIgnoreCase("V")) { DBSession dbs = (DBSession) incomingRequest.get("dbsession"); String queryString = "from CatalogSecurity as cs " + "where cs.catalogId = ? and cs.itemNumber != '0' " + "and cs.accessType = ? "; List resultList = dbs.query( queryString, new Object[] {catalogId, accesType}, new Type[] {Hibernate.STRING, Hibernate.STRING}); if (resultList != null && resultList.size() > 0) { for (int i = 0; i < resultList.size(); i++) { CatalogSecurity catalogItemSecurity = (CatalogSecurity) resultList.get(i); if (!accessId.equalsIgnoreCase(catalogItemSecurity.getAccessId())) { PuridiomProcessLoader processLoader = new PuridiomProcessLoader((String) incomingRequest.get("organizationId")); PuridiomProcess process = processLoader.loadProcess("catalogsecurity-add.xml"); Map updateParameters = new HashMap(); updateParameters.put("organizationId", organizationId); updateParameters.put("dbsession", incomingRequest.get("dbsession")); updateParameters.put( "CatalogSecurity_catalogId", (String) catalogSecurity.getCatalogId()); updateParameters.put( "CatalogSecurity_itemNumber", (String) catalogItemSecurity.getItemNumber()); updateParameters.put( "CatalogSecurity_accessType", (String) catalogSecurity.getAccessType()); updateParameters.put( "CatalogSecurity_accessId", (String) catalogSecurity.getAccessId()); updateParameters.put("CatalogSecurity_owner", (String) catalogSecurity.getOwner()); updateParameters.put("CatalogSecurity_dateEntered", today); updateParameters.put("CatalogSecurity_dateChanged", today); updateParameters.put( "CatalogSecurity_lastChangedBy", (String) catalogSecurity.getCatalogId()); process.executeProcess(updateParameters); catalogSecurity.setAccessId(accessId); dbs.add(catalogSecurity); if (dbs.getStatus() != Status.SUCCEEDED) { throw new TsaException( "error ocurred at update catalog security from for " + catalogSecurity.getItemNumber()); } } } } } this.setStatus(Status.SUCCEEDED); } catch (Exception e) { this.setStatus(Status.FAILED); Log.error(this, "An Error occurred at CatalogItemSecurityAddFromCatalog" + e); e.printStackTrace(); throw e; } return result; }
public void mergeAppend(PeekingIterator<T> data) throws JournalException { if (lagMillis == 0) { throw new JournalException("This journal is not configured to have lag partition"); } beginTx(); if (data == null || data.isEmpty()) { return; } long dataMaxTimestamp = getTimestamp(data.peekLast()); long hard = getAppendTimestampLo(); if (dataMaxTimestamp < hard) { return; } final Partition<T> lagPartition = openOrCreateLagPartition(); this.doDiscard = true; this.doJournal = true; long dataMinTimestamp = getTimestamp(data.peekFirst()); long lagMaxTimestamp = getMaxTimestamp(); long lagMinTimestamp = lagPartition.size() == 0L ? 0 : getTimestamp(lagPartition.read(0)); long soft = Math.max(dataMaxTimestamp, lagMaxTimestamp) - lagMillis; if (dataMinTimestamp > lagMaxTimestamp) { // this could be as simple as just appending data to lag // the only complication is that after adding records to lag it could swell beyond // the allocated "lagSwellTimestamp" // we should check if this is going to happen and optimise copying of data long lagSizeMillis; if (hard > 0L) { lagSizeMillis = dataMaxTimestamp - hard; } else if (lagMinTimestamp > 0L) { lagSizeMillis = dataMaxTimestamp - lagMinTimestamp; } else { lagSizeMillis = 0L; } if (lagSizeMillis > lagSwellMillis) { // data would be too big and would stretch outside of swell timestamp // this is when lag partition should be split, but it is still a straight split without // re-order Partition<T> tempPartition = createTempPartition().open(); splitAppend(lagPartition.bufferedIterator(), hard, soft, tempPartition); splitAppend(data, hard, soft, tempPartition); replaceIrregularPartition(tempPartition); } else { // simplest case, just append to lag lagPartition.append(data); } } else { Partition<T> tempPartition = createTempPartition().open(); if (dataMinTimestamp > lagMinTimestamp && dataMaxTimestamp < lagMaxTimestamp) { // // overlap scenario 1: data is fully inside of lag // // calc boundaries of lag that intersects with data long lagMid1 = lagPartition.indexOf(dataMinTimestamp, BSearchType.OLDER_OR_SAME); long lagMid2 = lagPartition.indexOf(dataMaxTimestamp, BSearchType.NEWER_OR_SAME); // copy part of lag above data splitAppend(lagPartition.bufferedIterator(0, lagMid1), hard, soft, tempPartition); // merge lag with data and copy result to temp partition splitAppendMerge( data, lagPartition.bufferedIterator(lagMid1 + 1, lagMid2 - 1), hard, soft, tempPartition); // copy part of lag below data splitAppend( lagPartition.bufferedIterator(lagMid2, lagPartition.size() - 1), hard, soft, tempPartition); } else if (dataMaxTimestamp < lagMinTimestamp && dataMaxTimestamp <= lagMinTimestamp) { // // overlap scenario 2: data sits directly above lag // splitAppend(data, hard, soft, tempPartition); splitAppend(lagPartition.bufferedIterator(), hard, soft, tempPartition); } else if (dataMinTimestamp <= lagMinTimestamp && dataMaxTimestamp < lagMaxTimestamp) { // // overlap scenario 3: bottom part of data overlaps top part of lag // // calc overlap line long split = lagPartition.indexOf(dataMaxTimestamp, BSearchType.NEWER_OR_SAME); // merge lag with data and copy result to temp partition splitAppendMerge( data, lagPartition.bufferedIterator(0, split - 1), hard, soft, tempPartition); // copy part of lag below data splitAppend( lagPartition.bufferedIterator(split, lagPartition.size() - 1), hard, soft, tempPartition); } else if (dataMinTimestamp > lagMinTimestamp && dataMaxTimestamp >= lagMaxTimestamp) { // // overlap scenario 4: top part of data overlaps with bottom part of lag // long split = lagPartition.indexOf(dataMinTimestamp, BSearchType.OLDER_OR_SAME); // copy part of lag above overlap splitAppend(lagPartition.bufferedIterator(0, split), hard, soft, tempPartition); // merge lag with data and copy result to temp partition splitAppendMerge( data, lagPartition.bufferedIterator(split + 1, lagPartition.size() - 1), hard, soft, tempPartition); } else if (dataMinTimestamp <= lagMinTimestamp && dataMaxTimestamp >= lagMaxTimestamp) { // // overlap scenario 5: lag is fully inside of data // // merge lag with data and copy result to temp partition splitAppendMerge(data, lagPartition.bufferedIterator(), hard, soft, tempPartition); } else { throw new JournalRuntimeException( "Unsupported overlap type: lag min/max [%s/%s] data min/max: [%s/%s]", Dates.toString(lagMinTimestamp), Dates.toString(lagMaxTimestamp), Dates.toString(dataMinTimestamp), Dates.toString(dataMaxTimestamp)); } replaceIrregularPartition(tempPartition); } }
public void execute() throws Exception { // TODO Auto-generated method stub Long key = (Long) getView().getAllValues().get("id"); System.out.println("\n\n\n\n\n\n\n\n\n\n The value sent===" + getView().getAllValues()); Map payingAcct = (Map) getView().getAllValues().get("payingAccount"); PaymentBatch batch = XPersistence.getManager().find(PaymentBatch.class, key); TransitAccount debitAccount = batch.getPayingAccount(); if (payingAcct.get("id") != null) { debitAccount = (TransitAccount) MapFacade.findEntity("TransitAccount", payingAcct); batch.setPayingAccount(debitAccount); XPersistence.getManager().merge(batch); } if (UserManager.loginUserHasRole("funder") && debitAccount == null) { addError("As funder, You Need to Attach Debit Account", null); return; } Long transId = (Long) getView().getObject("transId"); Boolean fina = (Boolean) getView().getObject("final"); if (fina) { if (debitAccount == null) { addError(" Debit Account Yet To be Attached", null); return; } String token = (String) getView().getObject("token"); String softToken = (String) getView().getValue("softToken"); if (Is.empty(softToken)) { addError("Soft Token Is Required", null); return; } DateTime dT = (DateTime) getView().getObject("fiveMinutes"); DateTime presentTime = new DateTime(Dates.withTime(Dates.createCurrent())); if (!Is.equalAsStringIgnoreCase(token, softToken)) { addError("Incorrect Soft Token", null); return; } if (dT.getMillis() < presentTime.getMillis()) { addError("Token Has Expired", null); return; } System.out.println( "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n The sent object to this place ===" + transId); } Transaction transaction = XPersistence.getManager().find(Transaction.class, transId); AsyncEventBus eventBus = new AsyncEventBus(Executors.newCachedThreadPool()); eventBus.register(transaction); System.out.println(" 1111111approve already commented out......... "); eventBus.post(new Object()); // transaction.approve(); closeDialog(); setNextMode(LIST); }
public void test_difference_minutes() { Date d1 = Dates.newDate(2010, 1, 1, 10, 30, 0); Date d2 = Dates.newDate(2010, 1, 1, 10, 0, 0); assertEquals(30, Dates.differenceMinutes(d1, d2)); }