I need to put multiple parameters in transaction in JAVA drived for ArangoDB;
It works with single parameter:
public String save(User user) throws ArangoDBException {
TransactionOptions options = new TransactionOptions().params(user).writeCollections(collectionName);
String action = "function (params) { "
+ "var db = require('internal').db; "
+ "var doc = params;"
+ "db.users.save(doc);"
+ "}";
return db.transaction(action, String.class, options);
}
But if I need to pass multiple parameters, then I'm stuck. Tried to pass map, arraylist or array, but it doesn't seem to work:
public void save(User user, User user2) throws ArangoDBException {
Map<String, Object> parameters = new MapBuilder()
.put("user", user)
.put("user2" user2)
.get();
TransactionOptions options = new TransactionOptions().params(parameters).writeCollections(collectionName);
String action = "function (params) { "
+ "var db = require('internal').db; "
+ "var doc = params['user'];"
+ "var doc2 = params['user2'];"
+ "db.users.save(doc);"
+ "db.users.save(doc2);"
+ "}";
db.transaction(action, String.class, options);
}
The need of your workaround is not necessary any more. The missing automatic serialization of map/list/array within TransactionOptions was a bug in the java-driver which is fixed with version 4.1.5
Had to serialize the map:
TransactionOptions().params(db.util().serialize(params)).writeCollections(collectionName, "users2");
Related
We have a Dataflow pipeline, everytime the side input refresh we have seen the table who cache data and during the refresh there are not all data inside. Obviously the rest of pipeline continue to work with raw data. Is there a possibility to fix it?
to not lose the data
this is the script
PCollection<TableRow> sideInput=pipeline
.apply(GenerateSequence.from(0).withRate(1, Duration.standardSeconds(180)))
.apply(Window.<Long>into(new GlobalWindows()) .triggering(Repeatedly.forever(AfterProcessingTime.pastFirstElementInPane())).discardingFiredPanes())
.apply("REFRESH-SIDEINPUT", ParDo.of(new SideInputQuery(psToBqOptions.getBQProjectSideInput())));
PCollectionView<Map<String, String>> sideInputView = sideInput
.apply("To map", ParDo.of(new TableRowToMap()))
.apply(View.<String, String>asMap());
public class SideInputQuery extends DoFn<Long, TableRow> {
private ValueProvider<String> ProjectIdRefresh;
PubSubToBqOptions psToBqOptions;
private static final Logger LOG = LoggerFactory.getLogger(SideInputQuery.class);
public SideInputQuery(ValueProvider<String> ProjectIdRefresh)
{
this.ProjectIdRefresh = ProjectIdRefresh;
}
#ProcessElement
public void processElement(ProcessContext c) throws Exception {
BigQuery bigQuery = BigQueryOptions.getDefaultInstance().getService();
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder("SELECT distinct storeId as storeID_rebuild, "
+ "cast(C.code as INT64) as storeId "
+ "FROM `" + ProjectIdRefresh.get() + ".{dataser}.{table}` s INNER JOIN UNNEST(s.{field}) as C on (C.type='type') "
+ "where 1=1 ").build();
TableResult results = bigQuery.query(queryConfig);
System.out.println(results);
for(FieldValueList fvl:results.iterateAll())
{
TableRow tr = new TableRow();
tr.set("storeId", fvl.get("storeId").getNumericValue());
tr.set("storeID_rebuild", fvl.get("storeID_rebuild").getNumericValue());
LOG.info("storeId" + fvl.get("storeId").getNumericValue() + " storeID_rebuild" + fvl.get("storeID_rebuild").getNumericValue());
c.output(tr);
}
}
}
I'am trying to get User object from json by Jayway JsonPath.
My class is:
public class User{
private String id;
private String name;
private String password;
private String email;
/*getters setters constructor*/
}
And json example:
{
"user": [
{
"id": "1",
"login": "client1",
"password": "qwerty",
"email": "client#gmail.com"
}
]
}
I wanna to get smth like this:
public Optional<User> find(String id) throws NoSuchEntityException {
Optional<User> user = Optional.empty();
try{
Path path = Path.of(fileDestination+fileName);
ReadContext ctx = JsonPath.parse(Files.readString(path));
User readUser = ctx.read("$..user[*]",User.class,Filter.filter(where("id").is(id)));
user = Optional.ofNullable(readUser);
} catch (IOException e) {
e.printStackTrace();
}
return user;
}
Or to get good advice how to code it:D
two things here
you must use the placeholder ? instead of * when you're filtering, otherwise, the filter will be ignored.
read() will return a list, not a single object.
so, I think, you need something like this
String json = "{\r\n"
+ " \"user\": [\r\n"
+ " {\r\n"
+ " \"id\": \"1\",\r\n"
+ " \"login\": \"client1\",\r\n"
+ " \"password\": \"qwerty\",\r\n"
+ " \"email\": \"client#gmail.com\"\r\n"
+ " }\r\n"
+ " ]\r\n"
+ "}";
Predicate filterById = filter(where("id").is("1"));
List<User> users = JsonPath.parse(json).read("$.user[?]",filterById );
System.out.println(users);
Reference: Filter Predicates
where("category").is("fiction").and("price").lte(10D) );
List<Map<String, Object>> books =
parse(json).read("$.store.book[?]", cheapFictionFilter);
Notice the placeholder ? for the filter in the path. When multiple filters are provided they are applied in order where the number of placeholders must match the number of provided filters. You can specify multiple predicate placeholders in one filter operation [?, ?], both predicates must match.
I was trying understand TestReporter in Junit5
#BeforeEach
void beforeEach(TestInfo testInfo) {
}
#ParameterizedTest
#ValueSource(strings = "foo")
void testWithRegularParameterResolver(String argument, TestReporter testReporter) {
testReporter.publishEntry("argument", argument);
}
#AfterEach
void afterEach(TestInfo testInfo) {
// ...
}
what is the use of publishEntry in TestReporter,
Can someone explain me.. Thanks in Advance..
"TestReporter" in conjunction with "TestInfo" gives an instance of the current test, this way you can get info about your actual test. and then publish it, in this example used as kind of logger.
StringBuffer is used for his mutable, fast, and synchonized characteristics, required for a test.
public class TestReporterTest {
StringBuffer sbtags = new StringBuffer();
StringBuffer displayName = new StringBuffer();
StringBuffer className = new StringBuffer();
StringBuffer methodName = new StringBuffer();
#BeforeEach
void init(TestInfo testInfo) {
className.delete( 0, className.length());
className.append( testInfo.getTestClass().get().getName());
displayName.delete( 0, displayName.length());
displayName.append( testInfo.getDisplayName());
methodName.delete( 0, methodName.length());
methodName.append( testInfo.getTestMethod().get().getName());
}
#Test
#DisplayName("testing on reportSingleValue")
void reportSingleValue(TestReporter testReporter) {
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry("algun mensaje de estatus");
}
#Test
void reportKeyValuePair(TestReporter testReporter) {
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry("una Key", "un Value");
}
#Test
void reportMultiKeyValuePairs(TestReporter testReporter) {
Map<String, String> map = new HashMap<>();
map.put("Fast and Furious 8","2018");
map.put("Matrix","1999");
testReporter.publishEntry( "className : " + className);
testReporter.publishEntry( "displayName: " + displayName);
testReporter.publishEntry("methodName : " + methodName);
testReporter.publishEntry(map);
}
}
Running the Test
timestamp = 2019-11-22T12:02:45.898, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.904, value = displayName: testing on reportSingleValue
timestamp = 2019-11-22T12:02:45.904, value = methodName : reportSingleValue
timestamp = 2019-11-22T12:02:45.904, value = algun mensaje de estatus
timestamp = 2019-11-22T12:02:45.919, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.920, value = displayName: reportMultiKeyValuePairs(TestReporter)
timestamp = 2019-11-22T12:02:45.920, value = methodName : reportMultiKeyValuePairs
timestamp = 2019-11-22T12:02:45.921, Fast and Furious 8 = 2018, Matrix = 1999
timestamp = 2019-11-22T12:02:45.924, value = className : TestReporterTest
timestamp = 2019-11-22T12:02:45.925, value = displayName: reportKeyValuePair(TestReporter)
timestamp = 2019-11-22T12:02:45.925, value = methodName : reportKeyValuePair
timestamp = 2019-11-22T12:02:45.925, una Key = un Value
Apart from the previous answers, When we are writing junit test scripts if we want to get some information out of the process we normally do System.out.println which is not recommended in corporate/enterprise world. Specially in code reviews, peer reviews we are advised to remove all the System.out.println from the code base. So in the junit world if we want to push or publish out of the scripts we are advised to use TestReporter publishEntry() method. With the combination of TestInfo we could read several information out of the original junit scripts.
Hope this facts also support your question.
The method name suggests you are publishing a new entry to the report, which is supported by the Java Doc for 5.3.0
https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/TestReporter.html
This would allow you to add additional, useful information to the test report; perhaps you would like to add what the tests initial conditions are to the report or some environmental information.
How do I fetch child user stories with Java client using Rally API?
Using Chrome's Postman client with URL https://us1.rallydev.com/slm/webservice/v2.0/HierarchicalRequirement/ObjectId/Children, I am able to fetch the children user stories.
But when I try with a Java client, like this:
QueryRequest request = new QueryRequest("/HierarchicalRequirement/ObjectId/Children");
it doesn't work.
Any pointer would be helpful.
It will take fetching "Children" collection on user stories and then hydrating it in a separate request. Here is an example based on latest version of Rally toolkit for Java:
public class GetChildStories {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String applicationName = "Find Child Stories of Epics filtered by Tag";
String workspaceRef = "/workspace/12352608129";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
restApi.setApplicationName(applicationName);
storyRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID", "Tags", "Children"}));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setQueryFilter((new QueryFilter("Tags.Name", "contains", "\"tag1\"")).and(new QueryFilter("DirectChildrenCount", ">", "0")));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println("Successful: " + storyQueryResponse.wasSuccessful());
System.out.println("Size: " + storyQueryResponse.getTotalResultCount());
for (int i=0; i<storyQueryResponse.getTotalResultCount();i++){
JsonObject storyJsonObject = storyQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name") + " FormattedID: " + storyJsonObject.get("FormattedID"));
QueryRequest childrenRequest = new QueryRequest(storyJsonObject.getAsJsonObject("Children"));
childrenRequest.setFetch(new Fetch("Name","FormattedID"));
int numberOfChildren = storyJsonObject.get("DirectChildrenCount").getAsInt();
System.out.println(numberOfChildren);
//load the collection
JsonArray children = restApi.query(childrenRequest).getResults();
for (int j=0;j<numberOfChildren;j++){
System.out.println("Name: " + children.get(j).getAsJsonObject().get("Name") + children.get(j).getAsJsonObject().get("FormattedID").getAsString());
System.out.println("Name: " + children.get(0).getAsJsonObject().get("Name") + children.get(0).getAsJsonObject().get("FormattedID").getAsString());
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
I am able to get the iterations under the project object. Now how do I get the iteration I need under that project and then drill down to the stories in that iteration using the JAVA toolkit?
https://sandbox.rallydev.com/slm/webservice/v2.0/project/7191194697/iterations
Given a project:
String projectRef = "/project/1234";
You may scope your requests as follows:
iterationRequest.setProject(projectRef);
or
storyRequest.setProject(projectRef);
If you scoped a story request to a project, then you may query on stories by traversing Iteration.Name if you know the iteration already:
storyRequest.setQueryFilter(new QueryFilter("Iteration.Name", "=", "my Iteration 1"));
Here is a more complex example that returns stories assigned to iterations that fall within the timbox of a specific release. If, for example, you have 4 iterations per release, this code will return stories assigned to all four iterations.
If you code against the sandbox, replace the value in the host variable accordingly.
public class FindIterationsByReleaseDateAndStories {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
String applicationName = "Find Iterations by Release Dates and Stories";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion());
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("ReleaseStartDate", "ReleaseDate"));
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
releaseRequest.setProject(projectRef);
releaseRequest.setQueryFilter(new QueryFilter("Name", "=", "r1"));
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(0).getAsJsonObject();
System.out.println(releaseJsonObject.get("ReleaseStartDate"));
System.out.println(releaseJsonObject.get("ReleaseDate"));
String rsd = releaseJsonObject.get("ReleaseStartDate").getAsString();
String rd = releaseJsonObject.get("ReleaseDate").getAsString();
QueryRequest iterationRequest = new QueryRequest("Iteration");
iterationRequest.setFetch(new Fetch("Name","StartDate","EndDate"));
iterationRequest.setScopedDown(false);
iterationRequest.setScopedUp(false);
iterationRequest.setProject(projectRef);
iterationRequest.setQueryFilter(new QueryFilter("StartDate", ">=", rsd).and(new QueryFilter("EndDate", "<=", rd)));
QueryResponse iterationQueryResponse = restApi.query(iterationRequest);
int numberOfIteraitons = iterationQueryResponse.getTotalResultCount();
System.out.println("numberOfIteraitons " + numberOfIteraitons);
if(numberOfIteraitons >0){
for (int i=0;i<numberOfIteraitons;i++){
JsonObject iterationJsonObject = iterationQueryResponse.getResults().get(i).getAsJsonObject();
String iterationName = iterationJsonObject.get("Name").getAsString();
System.out.println("iteration: " + iterationName);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setProject(projectRef);
storyRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID","ScheduleState"}));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setQueryFilter(new QueryFilter("Iteration.Name", "=", iterationName));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println("Number of stories in " + iterationName + " :" + storyQueryResponse.getTotalResultCount());
for (int j=0; j<storyQueryResponse.getResults().size();j++){
JsonObject storyJsonObject = storyQueryResponse.getResults().get(j).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name") + " FormattedID: " + storyJsonObject.get("FormattedID") + " ScheduleState: " + storyJsonObject.get("ScheduleState"));
}
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}
UPDATE: as far as your question in the comment, the code above is equivalent of
https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement?query=((Iteration.Name = i1) AND (Project = /project/12352608219))
There are other ways to achive the same result. Iteration name may not be unique, hence the second condition by project ref. In the code the request's project is set first, that's why the query itself uses one condition, but effectively there are two. If you know your iteration's ref, or ObjectID then the same result will be returned from (Iteration = /iteration/123456789), and there is no need to filter by project since a reference or ObjectID are unique.
WS API doc is interactive.Test your queries in WS API and copy the resulting query URLs from the address bar if you want to see how queries are formed:
-Query in the context of the intended object: click on the work item type in the Object Model, e.g. Defect or HierarchicalRequirement before typing your query in the query box.
-Enter a query in a box, e.g (Iteration.Name = i1)
-Click on Query button
-Results are displayed in the window from which you can copy query URL from address bar of your browser.