How to invoke formatter programmatically in Xtext and get output string - xtext

Instead of calling save on resource I would like to convert model to string programmatically.
I have already implemented formatter and tests for it so I would like to reuse it.
Is it possible, and if possible how?

#Inject
private Provider<ResourceSet> rsp;
#Inject
private ISerializer ser;
...
ResourceSet rs = rsp.get();
Resource r = rs.createResource(URI.createURI("dummy.mydsl"));
r.getContents().add(myModel);
System.out.println(ser.serialize(myModel, SaveOptions.newBuilder().format().getOptions());

Related

Dart extension: don't access members with 'this' unless avoiding shadowing

I'm learning to use the new Dart extension methods.
I'm doing this:
extension StringInsersion on StringBuffer {
void insertCharCodeAtStart(int codeUnit) {
final end = this.toString();
this.clear();
this.writeCharCode(codeUnit);
this.write(end);
}
int codeUnitAt(int index) {
return this.toString().codeUnitAt(index);
}
}
So that I can do something like this:
myStringBuffer.insertCharCodeAtStart(0x0020);
int value = myStringBuffer.codeUnitAt(2);
However, I get the following lint warning:
Don't access members with this unless avoiding shadowing.
Should I be doing something different?
The warning you received means the following:
There is no need to reference the current instance using keyword this. Everything will work without reference to the current instance because the static extension method itself acts as an instance method of extensible type.
Simply put, just remove the reference to the current instance from your code.
From this:
final end = this.toString();
To this:
final end = toString();
It's a style thing, based on Dart's guide. There are examples in https://dart-lang.github.io/linter/lints/unnecessary_this.html.
You can find more about style in https://dart.dev/guides/language/effective-dart/style.
I turn off this rule globally by changing "analysis_options.yaml"
include: package:flutter_lints/flutter.yaml
linter:
rules:
unnecessary_this: false

Is there support for routing on delete in repository or query annotation?

I'm trying to get working deletion of one document in spring data elasticsearch repository. And can't find way how to solve this error:
[userindex] RoutingMissingException[routing is required for
[userindex]/[address]/[12]
I have two linked documents:
#Document(indexName = "userindex", type = "user")
public class User {
#Field(index = FieldIndex.not_analyzed, type = FieldType.Long)
private Long userId;
...
}
#Document(indexName = "userindex", type = "address")
public class Address {
#Field(type = FieldType.String)
private String name;
#Field(index = FieldIndex.not_analyzed, type = FieldType.String)
private String addressId;
#Field(type = FieldType.String, store = true)
#Parent(type = "user")
private String parentId;
...
}
When I'm trying to delete one address via ElasticsearchCrudRepository<Address, Long> by using standard method delete(Long id) I receiving RoutingMissingException mentioned above.
If I'm trying to do it using ElasticSeach client, like this:
client.prepareDelete().setIndex("userindex")
.setType("address")
.setParent("user")
.setId(id.toString())
.execute().get();
everything works fine, but seems to me working directly with client is not the spring-data way.
Also I can't find any way how to customize delete method with annotation org.springframework.data.elasticsearch.annotations.Query.
I checked sources of org.springframework.data.elasticsearch.core.ElasticsearchTemplate and can't find any way how to add support for delete query.
Anybody knows how to solve it instead of using a client?
The version of spring-data-elasticsearch is 2.0.1
Update 03.05.2017
First of all, in my code was an error with my deletion, don't how it worked before, but it should be:
client.prepareDelete().setIndex("userindex")
.setType("address")
.setParent("500")
.setId(id.toString())
.execute().get();
Here 500 is parent id instead of type name.
And now about the spring-data way. There is no spring-data way in elasticsearch integration.
Proof:
DATAES-257
DATAES-331
If you want to do it the Spring way, you can use ElasticsearchTemplate which is much similar to RestTemplate.
ElasticsearchTemplate has deleteIndex() function which can delete the whole index. Also, you can do lots of other stuff with the template.
Example project with delete index is here: https://github.com/TechPrimers/spring-data-elastic-example-4/blob/master/src/main/java/com/techprimers/elastic/resource/SearchResource.java
Code:
#Autowired
ElasticsearchTemplate template;
template.deleteIndex(Users.class);

Overriding Joda DateTime toString in Groovy

So I'm using the JodaTime plugin in a grails project I'm implementing and I really don't like that it spits out the ISO8601 date format when I do a toString. I've been constantly putting toString and passing in the default.date.format from the messages file, but that's cumbersome. The majority of cases I just want it to do that automatically. So naturally it makes sense to take advantage of Groovy's fabulous metaprogramming to override toString on the DateTime class. But alas it doesn't work. Hence this discussion:
http://jira.codehaus.org/browse/GROOVY-4210
So according to said discussion, if our class implements an interface to implement the toString method we need to override the interface's metaclass. Looking at the joda code base, DateTime implements the ReadableDateTime interface which in turn inherits from ReadableInstant which is where the method signature is defined. The actual implementation is done 4 classes up in the class hierarchy for DateTime (DateTime inherits from BaseDateTime inherits from AbstractDateTime inherits from AbstractInstant which implements toString without parameters). With me so far?
So in theory this means I should override either the ReadableDateTime interface which doesn't actually have the toString signature or the ReadableInstant one which does. The following code to override toString on ReadableDateTime does nothing.
ReadableDateTime.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
So then trying with ReadableInstant:
ReadableInstant.metaClass.toString = { ->
delegate.toString(messageSource.getMessage(
'default.date.format', null, LCH.getLocale()))
}
also does not have the desired result for the DateTime.toString method. However, there are some interesting affects here. Take a look at the following code:
def aiToString = AbstractInstant.metaClass.getMetaMethod("toString", [] as Class[])
def adtToString = AbstractDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def bdtToString = BaseDateTime.metaClass.getMetaMethod("toString", [] as Class[])
def dtToString = DateTime.metaClass.getMetaMethod("toString", [] as Class[])
def date = new DateTime()
println "ai: ${aiToString.invoke(date)} "
println "adt: ${adtToString.invoke(date)} "
println "bdt: ${bdtToString.invoke(date)} "
println "dt: ${dtToString.invoke(date)} "
The first 3 methods show my date formatted just how I'd like it. The last one is still showing the ISO8601 formatted date. I thought maybe the JodaTime plugin for grails might be overriding the toString and they do add a few methods to these interfaces but nothing to do with toString. At this point, I'm at a loss. Anyone have ideas?
Thanks
You cann't override DateTime#toString(), becouse DateTime class is final
public final class DateTime
But if you want another date format, you can use toString(org.joda.time.format.DateTimeFormatter)
for example
def date = new DateTime();
date.toString(ISODateTimeFormat.basicDate()); // format yyyyMMdd

weird behavior using f# class with redis service stack lib

I'm testing a bit redis using .Net, I've read this tutorial
http://www.d80.co.uk/post/2011/05/12/Redis-Tutorial-with-ServiceStackRedis.aspx
and follow using c# and worked perfect, now when I'm trying translate this to f# I've a weird behavior, first I create a simple f# class (using type didn't work neither but it was expected)...basicaly the class is something like this:
//I ve used [<Class>] to
type Video (id : int, title : string , image : string , url : string) =
member this.Id = id
member this.Title = title
member this.Image = image
member this.Url = url
when I run the code, my db save an empty data, if I use a c# class inside my f# code this work, so I'm sure than the problem is the f# class...How can resolve this without depend c# code inside my f# code
Thanks !!!
Based on your tutorial, it looks like you want your F# Video class to be full of getter and setter properties instead of having a constructor with getters only as it is now (and it is a class, which you can verify by running it through FSI).
You can achieve this using a record type full of mutable fields (which is compiled down to a class type full of public getters and setters):
type Video = {
mutable Id : int
mutable Title : string
mutable Image : byte[]
mutable Url : string
}

Mocking FormsIdentity.Ticket.UserData with Moq

As part of a unit test I am trying to mock the return value of FormsIdentity.Ticket.UserData
The following will NOT work but it should give an idea of what I am trying to do:
var principal = Mock<IPrincipal>();
var formsIdentity = Mock<FormsIdentity>();
formsIdentity.Setup(a => a.Ticket.UserData).Returns("aaa | bbb | ccc");
principal.Setup(b => b.Identity).Returns(formsIdentity.Object);
The code I am trying to test looks something like this:
FormsIdentity fIdentity = HttpContext.Current.User.Identity as FormsIdentity;
string userData = fIdentity.Ticket.UserData;
All I want to do in my unit test is fake the return value from FormsIdentity.Ticket.UserData. But when I run the code in the first section I get an error when trying to mock the FormsIdentity. The error says the type to mock must be an interface, abstract class or non-sealed class.
I tried to use IIdentity instead of FormsIdentity (FormsIdentity is an implementation of IIdentity) but IIdentity doesn't have .Ticket.UserData.
So how can I write this test so that I get a value from FormsIdentity.Ticket.UserData?
I'm not a Unit Test expert, by any means, just getting my feet wet in the area.
Isn't it overkill to mock out the Identity in a unit test, because the Identity code is code that you can assume works already in isolation? (ie. it's Microsoft's code?) For example, when unit testing your own code, you wouldn't need to mock out one of the Framework objects. I mean, would you ever need to mock a List or a Dictionary?
That being said, if you REALLY want to test your code in isolation or for some reason have super fine control over the data returned in Userdata, can't you just write an Interface for the interaction between the Identity and your code?
Public Interface IIdentityUserData
Readonly Property UserData As String
End Interface
Public Class RealIdentityWrapper
Implements IIdentityUserData
Private _identity as FormsIdentity
Public Sub New(identity as FormsIdentity)
'the real version takes in the actual forms identity object
_identity = identity
End Sub
Readonly Property UserData As String Implements IIDentityUserData.UserData
If not _identity is nothing then
Return _identity.Ticket.UserData
End If
End Property
End Class
'FAKE CLASS...use this instead of Mock
Public Class FakeIdentityWrapper
Implements IIdentityUserData
Readonly Property UserData As String Implements IIDentityUserData.UserData
If not _identity is nothing then
Return "whatever string you want"
End If
End Property
End Class
'here's the code that you're trying to test...modified slightly
Dim fIdentity As FormsIdentity= HttpContext.Current.User.Identity
Dim identityUserData As IIdentityUserData
identityUserData =
'TODO: Either the Real or Fake implementation. If testing, inject the Fake implementation. If in production, inject the Real implementation
Dim userData as String
userData = identityUserData.UserData
Hope this helps

Resources