I am trying to read from a kind in google datastore and apply some transformations and write back to another kind. I am using google dataflow to achieve this. While reading from Datastore, we are able to give Kind. But not able to give Kind while writing. How to achieve this.
EDIT: Oops, I just noticed you were asking for Java. DatastoreIO.v1.write looks at the java equivalent of WriteToDatastore for me, in which case you have to set up your entity (including kind) in the previous step. Check out CreateEntityFn in this example. https://github.com/mbrukman/apache-beam/blob/master/examples/java/src/main/java/org/apache/beam/examples/cookbook/DatastoreWordCount.java#L197
ORIGINAL:
This is how I do it
import apache_beam
from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
from google.cloud.proto.datastore.v1 import entity_pb2
from googledatastore import helper
class MakeEntity(object):
def __init__(self, project):
self._project = project
def make(self, element):
try:
entity = entity_pb2.Entity()
helper.add_key_path(entity.key, 'EntityKind', element['id'])
helper.add_properties(entity, {
"created": datetime.datetime.now(),
"email": unicode(element['email'],
"count": int(element['count'],
"amount": float(element['amount'],
})
return entity
except:
logging.error(traceback.format_exc())
raise
def build_pipeline(project, pipeline_options):
p = apache_beam.Pipeline(options=pipeline_options)
_ = \
(p
# other transforms
| 'create entity' >> apache_beam.Map(MakeEntity(project=project).make)
| 'write to datastore' >> WriteToDatastore(project=project))
return p
Edit #2: I adjusted your code to more closely follow the example I linked to. Hopefully this works
public class ModifyEntityKindFn extends DoFn<Entity, Entity> {
#ProcessElement
public void processElement(ProcessContext context) {
Key.Builder keyBuilder = makeKey(NEW_KIND, inputEntity.getKey());
keyBuilder.getPartitionIdBuilder().setNamespaceId(NEW_NAMESPACE);
Entity.Builder entityBuilder = Entity.newBuilder().setKey(keyBuilder.build());
entityBuilder.getMutableProperties().put("content", makeValue(context.element()).build());
context.output(entityBuilder.build());
}
}
Related
In Xtext, how do I follow a reference from grammar B to grammar A, within a validator of grammar B (which is in the ui-plugin)? Consider the following example.
Grammar A is org.xtext.people.People
grammar org.xtext.people.People with org.eclipse.xtext.common.Terminals
generate people "http://www.xtext.org/people/People"
People:
people+=Person*;
Person:
'person' name=ID ';';
and an instance
person Alice {citizenship "MN"; id "12345"; }
person Bob {citizenship "CH"; id "54321";}
person Malice {citizenship "XXX"; id "66666"; }
At an airport, entries of people are recorded.
enter Alice;
enter Bob;
enter Malice;
Entries are modelled with a second grammar B org.xtext.entries.Entries
grammar org.xtext.entries.Entries with org.eclipse.xtext.common.Terminals
generate entries "http://www.xtext.org/entries/Entries"
import "http://www.xtext.org/people/People"
Entries:
entries+=Entry*;
Entry:
'enter' person=[Person] ';';
After ensuring that the Eclipse project org.xtext.entries has the project org.xtext.people on it's classpath, and ensuring that the org.xtext.entries plugin has the org.xtext.people as a dependency, all works as expected.
There is a travel ban on people from country XXX, although certain deserving people are excluded. Only the CIA knows who is excluded from the ban. Entries must not be allowed for people from XXX unless excluded.
The updated grammar is
grammar org.xtext.entries.Entries with org.eclipse.xtext.common.Terminals
generate entries "http://www.xtext.org/entries/Entries"
import "http://www.xtext.org/people/People"
Entries:
entries+=Entry*;
Entry:
travelBanOverride=TravelBanOverride?
'enter' person=[Person] ';';
TravelBanOverride: '#TravelBanOverride' '(' code=STRING ')';
with validator
package org.xtext.entries.validation
import org.eclipse.xtext.validation.Check
import org.xtext.entries.entries.EntriesPackage
import org.xtext.entries.entries.Entry
import org.xtext.entries.CIA
class EntriesValidator extends AbstractEntriesValidator {
public static val BAN = 'BAN'
public static val ILLEGAL_OVERRIDE = 'ILLEGAL_OVERRIDE'
#Check
def checkBan(Entry entry) {
if (entry.person.citizenship == "XXX") {
if (entry.travelBanOverride === null) {
error('Violation of Travel Ban', EntriesPackage.Literals.ENTRY__PERSON, BAN)
}
else {
val overridecode = entry.travelBanOverride.code;
val valid = CIA.valid(entry.person.name, entry.person.id, overridecode)
if (!valid) {
error('Illegal override code', EntriesPackage.Literals.ENTRY__TRAVEL_BAN_OVERRIDE, ILLEGAL_OVERRIDE)
}
}
}
}
}
where the driver for the external CIA web-app is modelled for example by
package org.xtext.entries;
public class CIA {
public static boolean valid(String name, String id, String overrideCode) {
System.out.println("UNValid["+name+","+overrideCode+"]");
return name.equals("Malice") && id.equals("66666") && overrideCode.equals("123");
}
}
The validations work as expected.
I now wish to provided a quick-fix for BAN, that checks for an override code from the CIA.
package org.xtext.entries.ui.quickfix
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider
import org.eclipse.xtext.ui.editor.quickfix.Fix
import org.xtext.entries.validation.EntriesValidator
import org.eclipse.xtext.validation.Issue
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor
import org.xtext.entries.entries.Entry
import org.xtext.entries.Helper
class EntriesQuickfixProvider extends DefaultQuickfixProvider {
#Fix(EntriesValidator.BAN)
def tryOverride(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Try override', 'Override if CIA says so.', 'override.png')
[element ,context |
val entry = element as Entry
// val person = entry.person // no such attribute
//val person = Helper.get(entry); // The method get(Entry) from the type Helper refers to the missing type Object
]
}
}
The first commented line does not compile: there is no attribute person. The second commented line is an attempt to solve the problem by getting a helper class in org.xtext.entries to get the person, but this does not compile either, giving a "The method get(Entry) from the type Helper refers to the missing type Object" error message.
For completeness, here is that helper.
package org.xtext.entries
import org.xtext.people.people.Person
import org.xtext.entries.entries.Entry
class Helper {
static def Person get(Entry entry) {
return entry.person;
}
}
Further, entry.travelBanOverride compiles fine, but entry.person does not. Clicking on Entry in Eclipse takes one to the expected code, which has both travelBanOverride and person.
The issue does not occur with a Java class in the same project and package.
package org.xtext.entries.ui.quickfix;
import org.xtext.entries.entries.Entry;
import org.xtext.people.people.Person;
public class Test {
public static void main(String[] args) {
Entry entry = null;
Person p = entry.getPerson();
}
}
Rewriting the quickfix in Java solves the problem.
package org.xtext.entries.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
import org.eclipse.xtext.ui.editor.quickfix.Fix;
import org.xtext.entries.validation.EntriesValidator;
import org.eclipse.xtext.validation.Issue;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor;
import org.xtext.entries.entries.Entry;
import org.xtext.entries.Helper;
import org.eclipse.xtext.ui.editor.model.edit.IModificationContext;
import org.eclipse.xtext.ui.editor.model.edit.ISemanticModification;
import org.eclipse.emf.ecore.EObject;
import org.xtext.entries.entries.Entry;
import org.xtext.people.people.Person;
public class EntriesQuickfixProvider extends DefaultQuickfixProvider {
#Fix(EntriesValidator.BAN)
public void tryOverride(final Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue,
"Try to override",
"Override",
"override.gif",
new ISemanticModification() {
public void apply(EObject element, IModificationContext context) {
Entry entry = (Entry) element;
System.out.println(entry.getPerson());
}
}
);
}
}
How do I follow a reference from grammar B (Entries) to grammar A (People), within a validator of grammar B?
My mistake is the following.
After ensuring that the Eclipse project org.xtext.entries has the
project org.xtext.people on it's classpath, and ensuring that the
org.xtext.entries plugin has the org.xtext.people as a dependency, all
works as expected.
The org.xtext.entries.ui ui-plugin must also have the org.xtext.people on its Java (Eclipse project) build path. Exporting and making a plugin-dependency it not enough.
Note that this setting should be made early, before crafting the quick-fix, because the Xtend editor has refreshing issues.
I am actually new in the world of Grails. I am trying to write a test case for domain class which is having some constraints . I am getting a Null pointer exception on my object when i am trying to run my unit test. On debugging I got to know that there is something fishy with my toString method which is causing the object to set as Null. How should I move ahead ? Any help is highly appreciated.
Here is my domain class:
#MultiTenant
class OrderCharge {
static scaffold = [
exclude: ['tenantId'],
]
static belongsTo = [
order: SalesOrder
]
MiscOrderCharges miscOrderCharges
Date lastUpdated
double quantity
double price
SapInvoiceRecord sapInvoice
static constraints = {
order(nullable: true)
quantity(min:1d)
miscOrderCharges()
sapInvoice(nullable: true)
}
String toString(){
def pattern = "\$##,###.00"
def currency = new DecimalFormat(pattern)
String rate = currency.format(miscOrderCharges.price)
return "$miscOrderCharges x$quantity"
}
}
Here is my Unit test case:
import grails.test.mixin.TestFor
import spock.lang.Unroll
import spock.lang.Specification
#TestFor(OrderCharge)
//#TestMixin(GroovyPageUnitTestMixin)
class ChargeSpec extends Specification {
def setup() {
mockForConstraintsTests(
OrderCharge, [
new OrderCharge(order: Mock(SalesOrder),
miscOrderCharges: Mock(MiscOrderCharges),
quantity: 1.0,
price:20.0
/*, sapInvoice: Mock(SapInvoiceRecord) */
)
]
)
}
void validateConstraints(obj, field, error) {
def validated = obj.validate()
if (error && error != 'valid') {
assert !validated
assert obj.errors[field]
assert error == obj.errors[field]
} else {
assert !obj.errors[field]
}
}
#Unroll("test inventory all constraints #field is #error")
def "test Charge all constraints"() {
given:
def obj = new OrderCharge("$field": val)
expect:
validateConstraints(obj, field, error)
where:
error |field |val
'nullable' |'orderCharge' |null
'nullable' |'sapInvoice' |null
'min' |'quantity' |-1
'min' |'price' |0
}
}
Thanks in advance.
The only thing that jumps out at me is your return in the toString().
return "$miscOrderCharges x$quantity"
You're using gStrings there. It's my understanding that individual variables can be referred to using simple $ notation, as in the format $somevariable, whereas expressions are in the format ${expression}.
In your statement x$quantity seems like a typo. Did you mean to multiply them as an expression like below?
return "${miscOrderCharges * quantity}"
See http://groovy.jmiguel.eu/groovy.codehaus.org/Strings+and+GString.html for more information.
Let's say I have a Joiner interface:
interface Joiner {
String join(List<String> l);
}
And two implementations of it:
class Java8Joiner implements Joiner {
#Override String join(List<String> l) { String.join("", l); }
}
class GroovyJoiner implements Joiner {
#Override String join(List<String> l) { l.join('') }
}
What is the best way to check that theses two implementation, or more, pass the same tests?
Basically, I want to run all the tests defined by JoinerSpecification with a Java8Joiner, then a GroovyJoiner, and so on...
class JoinerSpecification extends Specification {
#Subject
final def joiner = // Joiner instance here
def "Joining #list -> #expectedString"(List<String> list, String expectedString) {
expect:
joiner.join(list) == expectedString
where:
list | expectedString
[] | ''
['a'] | 'a'
['a', 'b'] | 'ab'
}
}
It is perfectly fine to refactor JoinerSpecification if needed.
My primary goals are:
Maintainable test code (with as little boilerplate as possible)
Clear error messages (which test of which implementation is failing)
Easy to run from the IDE
Edit 1 (15/06/2015)
Reworded my question & added some details to make it clearer.
Opal's proposal is interesting but is impractical. Not being able to use then blocks is a showstopper.
Lets try a self-answer using another approach. Since the goal is to execute the same specification on several implementations of the same interface, why not try to use good old inheritance ?
abstract class AbstractJoinerSpec extends Specification {
abstract Joiner getSubject()
#Unroll
def "Joining #list -> #expectedString"(List<String> list, String expectedString) {
given:
def joiner = getSubject()
expect:
joiner.join(list) == expectedString
where:
list | expectedString
[] | ''
['a'] | 'a'
['a', 'b'] | 'ab'
}
}
class Java8JoinerSpec extends AbstractJoinerSpec {
#Override
Joiner getSubject() { new Java8Joiner() }
}
class GroovyJoinerSpec extends AbstractJoinerSpec {
#Override
Joiner getSubject() { new Java8Joiner() }
}
Basically, the only abstract method is getSubject and all the inherited test cases are executed by Spock (I have not been able to find this feature in the documentation but it does work).
Pros
It only requires creating a tiny class for each implementation and the specification code remains clean.
The full power of Spock can be used
Error messages and reports are clear (you know which test failed for which implementation)
Cons
Running a given test for a given implementation from the IDE is not easy. You have to copy/paste the test case into the non abstract specification or remove the abstract modifiers and implement the getSubject method.
I thing the trade-off acceptable since you don't manually run/debug an implementation that often. Keeping the code clean, and having meaningful report worth this inconvenience.
What would be very useful here is comparison chaining but, as far as I know it's not implemented in groovy, see here. Since Subject purpose according to the docs is pure informational I've come up with the following ideas:
#Grab('org.spockframework:spock-core:0.7-groovy-2.0')
#Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
class Test extends Specification {
def 'attempt 1'() {
given:
def joiners = [new GroovyJoiner(), new Java8Joiner()]
expect:
joiners.every { it.join(list) == expectedString }
where:
list | expectedString
[] | ''
['a'] | 'a'
['a', 'b'] | 'ab'
}
def 'attempt 2'() {
given:
def gJoiner = new GroovyJoiner()
def jJoiner = new Java8Joiner()
expect:
[gJoiner.join(list), jJoiner.join(list), expectedString].toSet().size() == 1
where:
list | expectedString
[] | ''
['a'] | 'a'
['a', 'b'] | 'ab'
}
}
interface Joiner {
String join(List<String> l);
}
class Java8Joiner implements Joiner {
#Override String join(List<String> l) { String.join("", l); }
}
class GroovyJoiner implements Joiner {
#Override String join(List<String> l) { l.join('') }
}
In the attempt 1 I'm just checking if every element on the list is equal to expectedString. It looks nice however on error it's not verbose enough. Any element may fail and there's no trace which one.
The attempt 2 method makes use of Set. Since all the results should be equal there'll be only one element left in the collection. In prints verbose info on test failure.
What also comes to my head is guava's ComparisonChain but no idea if it would be useful as well as it's another project dependency.
Unfortunately, there is no way to create a cartesian product of two lists declaratively in Spock. You have to define your own Iterable that will provide the values for your variables.
There is a more readable (using Spock tabular data definition) way to define the data, if you are willing to sacrifice terseness for readability. Let me know if that interests you. Otherwise here is a solution that lets you define everything declaratively, without duplication, but you lose the nice tabular definitions of Spock.
If your implementation is stateless, i.e. it does not keep state, you can get away with using #Shared instances of Joiner:
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
interface Joiner {
String join(List<String> l);
}
class Java8Joiner implements Joiner {
#Override
String join(List<String> l) { String.join("", l); }
}
class GroovyJoiner implements Joiner {
#Override
String join(List<String> l) { l.join('') }
}
class S1Spec extends Specification {
#Shared
Joiner java8Joiner = new Java8Joiner()
#Shared
Joiner groovyJoiner = new GroovyJoiner()
List<Map> transpose(Map<List> mapOfLists) {
def listOfMaps = [].withDefault { [:] }
mapOfLists.each { k, values ->
[values].flatten().eachWithIndex { value, index ->
listOfMaps[index][k] = value
}
}
listOfMaps
}
Iterable distribute(List<Joiner> joiners, Map<String, List> data) {
def varsForEachIteration = transpose(data)
new Iterable() {
#Override
Iterator iterator() {
[joiners, varsForEachIteration].combinations().iterator()
}
}
}
#Unroll
def "Joining with #joiner #list -> #expectedString"() {
expect:
joiner.join(list) == expectedString
where:
[joiner, data] << distribute([java8Joiner, groovyJoiner], [
list : [[], ['a'], ['a', 'b']],
expectedString: ['', 'a', 'ab']
])
and:
list = data.list
expectedString = data.expectedString
}
}
Consider this code:
class Foo {
List<String> listOfStrings;
}
Using the smoke package, how can I get String by looking at listOfStrings ?
I see we can get a Declaration from a Type, but I don't see how to get the parameterized type from Declaration.
This is important for, among other things, building a serialization library.
That's not currently possible to do in smoke.
It might not even be possible to do with the mirrors API directly either. For example:
import 'dart:mirrors';
class B<T> {}
class A {
static B<int> b = new B<int>();
}
main() {
var x = reflectType(A);
print(x);
print(x.declarations[#b].type);
}
will print B, but not B<int>.
I have been trying to use scala.util.parsing.combinator.lexical.StdLexical but I'm not sure how to do it. I have been trying like this:
import scala.util.parsing.combinator.lexical.StdLexical
class Foo extends StdLexical {
def main(args: Array[String]) {
val input = """
class Main {
def main(args: Array[String]) {
println("hello world")
}
}
"""
val scanner = new Scanner(input)
println(scanner.first)
}
}
It compiles and runs but nothing is printed. Can anyone give me a simple example using this class? (Preferably I want to get all the tokens at once in a list or similar)
You don't get any output because you use class instead of object, thus your code is never executed.
To get all token, you must fetch them manually:
def loop(s: Scanner, token: Seq[Token]): Seq[Token] =
if (s.atEnd) token
else loop(s.rest, token :+ s.first)
println(loop(new Scanner(input), Vector()))
Nevertheless, StdLexical doesn't tokenise the complete Scala grammar. If you need this, I suggest to use Scalariform and its tokenise method.