Date relative to current in the DBUnit dataset - java

I'm wondering if there is any way to specify for example tomorrow as date in the DBUnit XML dataset. Sometimes code logic is different for dates in future and dates in the past and I want to test both cases. For sure I can specify something like the 5th of November 2239 and be sure that test will work till this date but are there more elegant way.
I haven't yet faced such situation during my Java development but once I had experience when code logic was different for one day before dates, two days before dates and more than two days before dates. In this case the only possible solution to write database driven test is to insert relative dates during data import.
Are there any facilities provided by the DBUnit for this?

I just started using DBUnit and was looking for similar capabilities. Unfortunately there doesn't seem to be an expression language for dates in the framework. However, I did find a suitable workaround using DBUnit's ReplacementDataSet class. This class takes an IDataSet object and exposes methods to replace objects extracted by the IDataSet object from the data set files.
dataset
<dataset>
<user first_name="Dan"
last_name="Smith"
create_date="[create_date]"/>
<dataset>
source code
String dataSetFile = "testDataFile.xml";
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new FileInputStream(dataSetFile));
ReplacementDataSet rDataSet = new ReplacementDataSet(dataSet);
Set<String> keys = dataSetAdjustments.keySet();
rDataSet.addReplacementObject("[create_date]", DateUtils.addDays(new Date(), -2));
Now, when the test runs the user's creation data will always be set to two days before the test was run.
Hope this helps. Good luck.

A new relative date/time syntax has been added in DbUnit 2.7.0 and you can now write [now+1d] to set tomorrow's date without any extra setup.
<dataset>
<user create_date="[now+1d]"/>
<dataset>
The doc is here:
http://dbunit.sourceforge.net/datatypes.html#relativedatetime
A few examples from the doc:
[now] : current date time
[now-1d] : the same time yesterday
[now+1y+1M-2h] : a year and a month from today, two hours earlier
[now+1d 10:00] : 10 o'clock tomorrow

I've managed to achieve that with something really similar to what #loyalBrown did, but I couldn't do exactly like that as some further information was missing there and I was instantiating my current datasource with #DatabaseSetup("/pathToXML")
So that's what I did:
First I needed to remove the annotation, you need now to start this .xml file programatically with the following code:
#Inject
protected DataSource dataSource;
#Before
public void setUp() throws Exception {
DataSourceDatabaseTester dataSourceDatabaseTester = new DataSourceDatabaseTester(dataSource);
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new FileInputStream(getClass().getResource(DATASET_FILE_LOCATION).getPath()));
ReplacementDataSet rDataSet = new ReplacementDataSet(dataSet);
rDataSet.addReplacementObject("{$today}", new Date());
dataSourceDatabaseTester.setDataSet(rDataSet);
dataSourceDatabaseTester.onSetup();
}
This seemed to do the trick

You can use add() of Calendar to define dates in the future and using this in relationship with datasource for JUnit. I doubt that this would work with DBUnit's XML format. May be you create your own TestCase which extends from DBTestCase and implement getDataSet() method.

Related

Scichart's setVisibleRange() having no effect

I'm trying to set the visible range of a DateAxis. Here's what I have:
final IXyDataSeries<Date, Double> dataSeries = sciChartBuilder.newXyDataSeries(Date.class, Double.class).build();
final IAxis xBottomAxis = sciChartBuilder.newDateAxis()
.withAxisId("xBottomAxis")
.build();
xBottomAxis.setAutoRange(AutoRange.Never);
xBottomAxis.setTextFormatting("MM.dd.yyyy h:mm a");
Calendar rightNow = Calendar.getInstance();
long t = rightNow.getTimeInMillis();
Date rightNowPlusFiveMin = new Date(t + (5 * ONE_MINUTE_IN_MILLIS));
Date rightNowMinusThreeHr = new Date(t - (3 * ONE_HOUR_IN_MILLIS));
xBottomAxis.setVisibleRange(new DateRange(rightNowMinusThreeHr, rightNowPlusFiveMin));
This should keep it from AutoRanging and set the default min and max on the xBottomAxis. Is this not how you do it?
Currently, it's just AutoRanging to fit the data.
Edit: Here are the applicable links for its documentation.
https://www.scichart.com/documentation/android/v2.x/webframe.html#Axis%20Ranging%20-%20VisibleRange%20and%20DataRange.html
https://www.scichart.com/documentation/android/v2.x/webframe.html#Axis%20Ranging%20-%20Setting%20and%20Getting%20VisibleRange.html
I tried to copy-paste your code in this example and it worked as expected - axis was rendered with assigned VisibleRange value.
I noticed that you used custom AxisId for your DateAxis. Does it mean that you have more than one XAxis and maybe your RenderableSeries is attached to wrong axis?
Also I would suggest you to update to the latest version of the library - it could be possible that if it's a bug then it's already fixed in latest build.
If it doesn't help then you'll need to provide more code or entire project which reproduces this issue because with code which you provided it's hard to tell what could be the cause of this issue.
It looks like removing mySciChartSurface.zoomExtents() fixed it. Link to zoomExtents documentation.
Thanks to Yura Khariton for the help.

How do I translate Datastore entity to BigQuery TableRow object in Java?

I have the following DoFN function that kind of does it but there is no documentation of questions I could find about it.
Problem No. 1 is how do I automatically translate keys so they are constructed in BigQuery in the same way that the BigQuery does it when importing form Datastore backup file?
Problem No. 2 is how to handle timestamps? The code below breaks the pipeline with following message:
JSON object specified for non-record field: timestamp
Here is a code I wrote:
public class SensorObservationEntityToRowFn extends DoFn<Entity, TableRow> {
/**
* In this example, put the whole string into single BigQuery field.
*/
#Override
public void processElement(ProcessContext c) {
Map<String, Value> props = getPropertyMap(c.element());
TableRow row = new TableRow();
row.set("id", c.element().getKey().getPathElement(c.element().getKey().getPathElementCount()-1).getId());
if (
props.get("property1") != null &&
props.get("property2") != null
) {
// Map data from the source Entity to the destination TableRow
row.set("property1", props.get("property1").getStringValue());
row.set("property2", props.get("property2").getStringValue());
}
row.set("source_type", props.get("source_type").getStringValue());
DateTime dateTime = new DateTime(props.get("timestamp").getTimestampMicrosecondsValue()/1000L);
row.set("timestamp", dateTime);
// Output new TableRow only if all data is present in the source
c.output(row);
}
}
My expectation was to find something in helper classes, but I was unsuccessful. Guess Google is still adding new bits to their APIs. Maybe in the next version.
The biggest problem is that the API is a little not intuitive and inconsistent with other parts. Entity's key should have it's own accessor method instead of having to dig in the ancestor path like this (get the last element of the path array):
getKey().getPathElement(c.element().getKey().getPathElementCount()-1).getId()
The second problem with timestamps: a little unelegant as well. I couldn't find anywhere in the documentation, how to format timestamp in Datastore or in BigQuery from the API point of view (data type, length of the field, its format, etc.). The solution that works now requires third party library ("joda"):
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
And the below data translation. You have to remember that it is in milliseconds in one place and in microseconds in another. Another unnecessary confusion.
DateTime dateTime = new DateTime(props.get("timestamp").getTimestampMicrosecondsValu‌​e()/1000L);
row.set("timestamp", ISODateTimeFormat.dateTime().print(dateTime));
Hope this helps others working with Dataflow and moving data from one place to another.

How do I use filters in jGit?

How do I use RevFilters in jGit?
I found an answer to a question I had about completing a particular task (getting the commits made between two dates), and the answer said to use a particular subclass of RevFilter. However, I don't know how to use RevFilters!
In particular, I would like to know what I need to do to take the answer in the question I linked to, which says
Date since = getClock();
Date until = getClock();
RevFilter between = CommitTimeRevFilter.between(since, until);
And use it to actually iterate over the commits between the two dates. Something like:
RevFilter between = CommitTimeRevFilter.between(since, until);
RevWalk walk = new RevWalk(repository);
walk.magicallyApplyFilters(between);
for(RevCommit commit : RevWalk) {
// Do my thing
}
I have read the jGit documentation. Sadly, in the section that would show how to use filters, there is the line:
TODO talk about filters
So the documentation does not help me. And although I get the impression that using filters is a basic part of using jGit, nobody else has asked how to use them on StackOverflow yet!
Judging by the source, all you need to do is create an instance of the RevWalk iterator, set the filter, then iterate over the walker.
RevWalk walk = new RevWalk(repo);
walk.markStart(walk.parseCommit(repo.resolve(Constants.HEAD)));
walk.sort(RevSort.REVERSE); // chronological order
final LocalDate thisYear = new LocalDate(2015, 1, 1); // joda
walk.setRevFilter(CommitTimeRevFilter.after(thisYear.toDate()));
for(RevCommit commit : walk) {
// do your thing
}
The filter is essentially just a predicate on whether or not a commit is yielded from the walker. There are a number of filters that you could use found in the org.eclipse.jgit.revwalk.filter package. Or you can create your own by extending the RevFilter class.

date validation in tapestry server side

Im trying to put some validation in the date field. The condition is the effective date field should be less or equal to the current date and it should be 1st of month.
Im doing it in tapestry.The data type is DATE. im using tapestry as yo know you will have .html page a, .java file and .page file. Im doing it in the java file . So please help me on this.
When the form is submitted t5 emits various events during the different stages. On EventConstants.VALIDATE is a good place to perform more complex validations that are not supported by t5 out of the box, or to perform cross-field validation serverside.
#Component
private Form myForm;
...
#OnEvent(value = EventConstants.VALIDATE, component = "myForm")
public void onCreateEditValidate() {
// do validation and if any error record it
myForm.record(theDateField, "Dang, try again!");
...
http://tapestry.apache.org/forms-and-validation.html
You can use the onValidate event too as stated at the end of the link jon martin solas posted.
Something like:
void onValidateFromYouDateFieldId(..) throws ValidationException{
//your custom validations
}
you can check out this example for more information:
http://jumpstart.doublenegative.com.au/jumpstart/examples/input/morevalidation
http://tapestry.apache.org/forms-and-validation.html#FormsandValidation-OverridingtheTranslatorwithEvents

sugarcrm editview coding help for newbi

I have an older version of sugarcrm 4.5 running.
Dont brake that aint broken.
I have a script i wrote that adds 30 days from current date to expected close date when creating a new opportunity, but the problem is everytime you edit the opportunity it adds 30 days, and not just when its is new. How do i tel Sugar to only look for new. this is in editview.php not a logic hook as i want to display the date in the field when creating.
Heres my code
var currentTime = new Date();
document.getElementsByName('date_closed')[0].value = (year = currentTime.getFullYear())+'-'+(month = currentTime.getMonth() + 2)+'-'+(day = currentTime.getDate());
regards
This should be done with a before save logic hook - you can test to see if the record has an id in the hook. If it has no id then you can assume its a new record.
More information on logic hooks can be found here (you are using a very old version of SugarCRM so not everything in this documentation will apply)
http://developers.sugarcrm.com/docs/OS/5.2/-docs-Developer_Guides-Developer_Guide_5.2-DevGuide%205.2.1.47.html

Categories

Resources