Inheriting from Own class instead from XMLParserRuleContext - antlr4

I am using the 'visitor' pattern to generate XML from my parsed code. On typical context class looks like:
public static class On_dtmContext extends ParserRuleContext {
public List<FieldContext> field() {
return getRuleContexts(FieldContext.class);
}
public TerminalNode ON() { return getToken(SRC_REP_SCREENParser.ON, 0); }
public On_dtm_headerContext on_dtm_header() {
return getRuleContext(On_dtm_headerContext.class,0);
}
.....
}
and I access the element in my visitors call back function using RuleContext's 'getText' member function.
I would like to write a class inheriting from 'ParserRuleContext' and overload 'getText' in order to replace characters like '<' or '>' with their xml escape sequences. Is there a way I can have my code generated and having the context classes inheriting from my class, as:
public static class On_dtmContext extends XMLParserRuleContext {
public List<FieldContext> field() {
return getRuleContexts(FieldContext.class);
}
public TerminalNode ON() { return getToken(SRC_REP_SCREENParser.ON, 0); }
public On_dtm_headerContext on_dtm_header() {
return getRuleContext(On_dtm_headerContext.class,0);
}
.....
}
Thank you for your help!
Kind regards, wolf

Is there a reason why you are trying to extend the class, rather than creating a parser rule in your grammar to capture < and > so you can translate them as they occur?
The parser rules would look something like:
lessThan
: '<'
;
greaterThan
: '>'
;
At that point, you would have specific visitors for each of those terms and could translate them as you will.

Related

Return derived type when return type is base type c#

I have a Base abstract Class and a Derived Class
Base abstract class
public abstract class BaseData: IListingData
{
private int? _photos;
public string DataKey { get; set; }
public abstract List<Images> Photos { get; set; }
}
Derived Class
public class DerivedData1 : BaseData
{
public override List<Images> Photos
{
get
{ return new List<Images>(); } set {}
}
}
public class DerivedData2 : BaseData
{
public override List<Images> Photos
{
get
{ return new List<Images>(); } set {}
}
}
I have a Service function:
public List<ListingData> FilterListings(PredicateHandler predicates)
{
//Retrieved from database and based on certain predicates, it will create List of DerivedData1 or DerivedData2
Return new List<DerivedData1>(); //This is where the ERROR is.
}
I am unable to return Derived Type. I tried casting and I get the following same compile error. Cannot convert expression type 'System.Collections.Generic.List< DerivedData1>' to return type 'System.Collections.Generic.List< ListingData>'
I also tried changing the return type of the service function FilterListings() to the Interface IListingData, but I still encounter the a casting error.
I searched on other Stackoverflow posts. Which answers the questions of returning a derived Type from within a Base class. But I think this is a different scenario.
Bottom line, My service-class function has a return type Animal() and from inside the function I want to return Dog()
What am I missing?
In your example code, you cannot return new List of DerivedData1 where the function return type is List of ListingData.
The reason is there is no hierarchical relations between the two list types.
What you can do is:
public List<ListingData> FilterListings(PredicateHandler predicates)
{
var list = new List<BaseData>();
var list.Add(new DerivedData1());
var list.Add(new DerivedData2());
return list;
}
I'd use List<object> if I were in your place, and cast object to whatever is needed when iterating (for example). Your issue is that List<Base> and List<DerivedFromBase> are treated as unrelated (which is the intended behaviour, even if uncomfortable).

Method aliasing in class with Groovy

I'm going to internationalize groovy API abit.
For final class (e.g. String)
String.metaClass.вСтроку = {-> this.toString() }
However, this will create additional closure. Isn't there any way to just alias method with another method?
Something like this:
String.metaClass.вСтроку = String.metaClass.&toString
You could use #Category transform like this
#Category(String) class StringInternationalization {
String вСтроку() {
this.toString()
}
int длина() {
this.length()
}
}
class ApplyMixin {
static {
String.mixin(StringInternationalization)
final helloString = "Привет мир!"
println helloString.вСтроку()
assert helloString.длина() == helloString.length()
}
}
new Main()
This will create 1 Category class for each localised class and one class to apply all mixin transformations(to register all methods.) Also should be faster, then individual closures.
More reading here: http://groovy.codehaus.org/Category+and+Mixin+transformations

XStreamAsAttribute not adding as attribute - xstream

I wrote a class which will be converted by xstream into xml .
I added #XStreamAsAttribute to add xmlns as an attribute . But it got added as a nested tag in the output
My class file is as follows
#XStreamAlias("GetConfigurationParametersResponse")
public class GetConfigurationParametersResponse
extends BaseResponse
{
#XStreamAlias("xmlns")
#XStreamAsAttribute
final String xmlns = "http://www.collab.net/teamforge/integratedapp";
#XStreamAlias("xmlns:ns2")
#XStreamAsAttribute
final String ns2="http://www.collab.net/teamforge/integratedapp";
#XStreamImplicit(itemFieldName="ConfigurationParameter")
protected List<ConfigurationParameter> configurationParameter;
public List<ConfigurationParameter> getConfigurationParameter() {
if (configurationParameter == null) {
configurationParameter = new ArrayList<ConfigurationParameter>();
}
return this.configurationParameter;
}
}
The output for this is as follows
<com.collabnet.teamforge.ia.GetConfigurationParametersResponse>
<xmlns>http://www.collab.net/teamforge/integratedapp</xmlns>
<ns2>http://www.collab.net/teamforge/integratedapp</ns2>
</com.collabnet.teamforge.ia.GetConfigurationParametersResponse>
But I need output as
<com.collabnet.teamforge.ia.GetConfigurationParametersResponse xmlns="http://www.collab.net/teamforge/integratedapp" xmlns:ns2="http://www.collab.net/teamforge/integratedapp">
</com.collabnet.teamforge.ia.GetConfigurationParametersResponse>
Please help in finding out where I am going wrong .
I followed this tutorial http://x-stream.github.io/annotations-tutorial.html
You probably need to do the following:
xstream.processAnnotations(GetConfigurationParametersResponse.class);
If only the following is being called:
xstream.processAnnotations(BaseResponse.class);
Then you could use the #XStreamInclude annotation on BaseResponse as follows:
#XStreamInclude({GetConfigurationParametersResponse.class})
public class BaseResponse {
}
What worked for me was:
xstream.autodetectAnnotations(true);

Use Groovy Category implicitly in all instance methods of class

I have simple Groovy category class which adds method to String instances:
final class SampleCategory {
static String withBraces(String self) {
"($self)"
}
}
I want to use this category in my unit tests (for example). It looks like this:
class MyTest {
#Test
void shouldDoThis() {
use (SampleCategory) {
assert 'this'.withBraces() == '(this)'
}
}
#Test
void shouldDoThat() {
use (SampleCategory) {
assert 'that'.withBraces() == '(that)'
}
}
}
What I'd like to achieve, however, is ability to specify that category SampleCategory is used in scope of each and every instance method of MyTest so I don't have to specify use(SampleCategory) { ... } in every method.
Is it possible?
You can use mixin to apply the category directly to String's metaClass. Assign null to the metaClass to reset it to groovy defaults. For example:
#Before void setUp() {
String.mixin(SampleCategory)
}
#After void tearDown() {
String.metaClass = null
}
#Test
void shouldDoThat() {
assert 'that'.withBraces() == '(that)'
}
Now you have the option to use extension modules instead of categories:
http://mrhaki.blogspot.se/2013/01/groovy-goodness-adding-extra-methods.html
On the plus side Intellij will recognize the extensions. I've just noticed that it doesn't even need to be a separate module as suggested by the link, just add META-INF/services/org.codehaus.groovy.runtime.ExtensionModule to the project:
# File: src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = module
moduleVersion = 1.0
extensionClasses = SampleExtension
The extension class is pretty much defined like a normal category:
class SampleExtension {
static String withBraces(String self) {
"($self)"
}
}
Can be used like:
def "Sample extension"() {
expect: 'this'.withBraces() == '(this)'
}
If you are using Spock there is a #Use annotation that can be used on the specifications. The drawback with that is that Intellij will not recognize it.

ViewHelper newable/injectable dilemma

I'm trying to design an application following Misko Heverys insights. It's an interesting experiment and a challenge. Currently I'm struggling with my ViewHelper implementation.
The ViewHelper decouples the model from the view. In my implementation it wraps the model and provides the API for the view to use. I'm using PHP, but I hope the implementation is readable for everyone:
class PostViewHelper {
private $postModel;
public function __construct(PostModel $postModel) {
$this->postModel = $postModel;
}
public function title() {
return $this->postModel->getTitle();
}
}
In my template (view) file this could be called like this:
<h1><?php echo $this->post->title(); ?></h1>
So far so good. The problem I have is when I want to attach a filter to the ViewHelpers. I want to have plugins that filter the output of the title() call. The method would become like this:
public function title() {
return $this->filter($this->postModel->getTitle());
}
I need to get observers in there, or an EventHandler, or whatever service (in what I see as a newable, so it needs to be passed in through the stack). How can I do this following the principles of Misko Hevery? I know how I can do this without it. I'm interested in how for I can take it and currently I don't see a solution. ViewHelper could be an injectable too, but then getting the model in there is the problem.
I didn't find the blog post you referenced very interesting or insightful.
What you are describing seems more like a Decorator than anything to do with dependency injection. Dependency injection is how you construct your object graphs, not their state once constructed.
That said, I'd suggest taking your Decorator pattern and running with it.
interface PostInterface
{
public function title();
}
class PostModel implements PostInterface
{
public function title()
{
return $this->title;
}
}
class PostViewHelper implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->post->title();
}
}
class PostFilter implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->post = $post;
}
public function title()
{
return $this->filter($this->post->title());
}
protected function filter($str)
{
return "FILTERED:$str";
}
}
You'd simply use whatever DI framework you have to build this object graph like so:
$post = new PostFilter(new PostViewHelper($model)));
I often use this approach when building complex nested objects.
One problem you might run into is defining "too many" functions in your PostInterface. It can be a pain to have to implement these in every decorator class. I take advantage of the PHP magic functions to get around this.
interface PostInterface
{
/**
* Minimal interface. This is the accessor
* for the unique ID of this Post.
*/
public function getId();
}
class SomeDecoratedPost implements PostInterface
{
public function __construct(PostInterface $post)
{
$this->_post = $post;
}
public function getId()
{
return $this->_post->getId();
}
/**
* The following magic functions proxy all
* calls back to the decorated Post
*/
public function __call($name, $arguments)
{
return call_user_func_array(array($this->_post, $name), $arguments);
}
public function __get($name)
{
return $this->_post->get($name);
}
public function __set($name, $value)
{
$this->_post->__set($name, $value);
}
public function __isset($name)
{
return $this->_post->__isset($name);
}
public function __unset($name)
{
$this->_post->__unset($name);
}
}
With this type of decorator in use, I can selectively override whatever method I need to provide the decorated functionality. Anything I don't override is passed back to the underlying object. Multiple decorations can occur all while maintaining the interface of the underlying object.

Resources