javaCC inserts non-wanted statements - java

I've got the following javacc grammar.
The rule UnaryExpr creates some anonymous classes implementing java.util.function.Predicate<>
options {
static=false;
DEBUG_PARSER=false;
IGNORE_CASE=true;
JDK_VERSION="1.8";
}
(...)
private Predicate<SAMRecord> UnaryExpr(): { }
{
(
<DUPLICATE> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getDuplicateReadFlag();}
};}
| <UNMAPPED> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadUnmappedFlag();}
};}
| <FAILSVENDORQUALITY> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadFailsVendorQualityCheckFlag();}
};}
| <PROPERPAIR> { return new Predicate<SAMRecord>() {
#Override public boolean test(final SAMRecord rec) { return rec.getReadPairedFlag();}
};}
)
}
when I'm generating the code using javacc 7.0.2, the generated java code contains some extra statements that break the code {if ("" != null). In the java file, instead or my original code:
#Override public boolean test(final SAMRecord rec) {return rec.getDuplicateReadFlag();}
I've got:
#Override public boolean test(final SAMRecord rec) { {if ("" != null) return rec.getDuplicateReadFlag();}}
How can I fix this ? Thanks .

That's a rather annoying behaviour.
Could you live with this?
private Predicate<SAMRecord> UnaryExpr(): {
class A implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getDuplicateReadFlag(); } }
class B implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadUnmappedFlag(); } }
class C implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadFailsVendorQualityCheckFlag(); } }
class D implements Predicate<SAMRecord> {
#Override public boolean test(final SAMRecord rec) {
return rec.getReadPairedFlag(); } }
}
{
( <DUPLICATE> { return new A() ; }
| <UNMAPPED> { return new B() ; }
| <FAILSVENDORQUALITY> { return new C() ; }
| <PROPERPAIR> { return new D() ; }
)
}

Related

void with Generics in Java

I have a function that returns void
public interface IProductService {
void delete(String id);
}
Generic method
public interface IRequestHandler<C , R> {
R handler(C c);
Class<C> commandType();
}
Implementation of generic interface
#Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Void> {
#Override
public Void handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
#Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}
How can I use void in IRequestHandler<DeleteProductCommand, Void> so that I can map void from iProductService.delete(deleteProductCommand.id);
Option 1:
Just return null:
#Override
public Void handler(DeleteProductCommand deleteProductCommand) {
iProductService.delete(deleteProductCommand.id);
return null;
}
Option 2:
Update the IProductService::delete method to return something meaningful, e.g. a boolean value like Collection::remove does:
public interface IProductService {
boolean delete(String id);
}
#Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Boolean> {
#Override
public Boolean handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
#Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}

How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class in Java

Any clue if it is possible to convert code below to Java (Android) from C#?
It is based on my prev.question
How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class
public class ItemPropertyChangedNotifyingList<T> : IList<T>, INotifyPropertyChanged where T : INotifyPropertyChanged
{
private List<T> _listImplementation = new List<T>();
public void Add(T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Add(item);
}
private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(sender, e);
}
public IEnumerator<T> GetEnumerator()
{
return _listImplementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_listImplementation).GetEnumerator();
}
public void Clear()
{
_listImplementation.ForEach(x => x.PropertyChanged -= ItemOnPropertyChanged);
_listImplementation.Clear();
}
public bool Contains(T item)
{
return _listImplementation.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_listImplementation.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
item.PropertyChanged -= ItemOnPropertyChanged;
return _listImplementation.Remove(item);
}
public int Count => _listImplementation.Count;
public bool IsReadOnly => false;
public int IndexOf(T item)
{
return _listImplementation.IndexOf(item);
}
public void Insert(int index, T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Insert(index, item);
}
public void RemoveAt(int index)
{
_listImplementation.RemoveAt(index);
}
public T this[int index]
{
get => _listImplementation[index];
set => _listImplementation[index] = value;
}
public event PropertyChangedEventHandler PropertyChanged;
}
Have we use PropertyChangeListener for this task? Like it is shown here.
public FocusManagerListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if ("focusOwner".equals(propertyName) {
...
} else if ("focusedWindow".equals(propertyName) {
...
}
}
...
}
I just ported ItemPropertyChangedNotifyingList to ItemChangeList.
In code, I changed this part.
Used 'ArrayList' to hold elements instead of 'List` in C#
In copyTo, I used Java 8 Stream. Since you tag 'android', I used Lightweight-Stream-API to achieve same feature of copyTo.
Java doesn't support get, set syntax, i divide to two methods.
import com.annimon.stream.Stream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ItemChangedList<T> {
private List<T> _listImplementation = new ArrayList<>();
private List<OnPropertyChangedObserver<T>> _changedObserverList = new ArrayList<>();
public static final String ITEM_ADDED = "bbed36af-0b7b-4e53-abc9-02d6a14d7f34";
public static final String ITEM_REMOVED = "7390116e-586d-4e62-9343-5b82b0a8c6c5";
public void add(T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(item);
}
public Iterator<T> iterator() {
return _listImplementation.iterator();
}
public void clear() {
for (T item : _listImplementation) {
sendPropertyChanged(item, ITEM_REMOVED);
}
_listImplementation.clear();
}
public boolean contains(T item) {
return _listImplementation.contains(item);
}
public void copyTo(T[] array, int arrayIndex) {
// Using https://github.com/aNNiMON/Lightweight-Stream-API
_listImplementation.addAll(Stream.of(array).skip(arrayIndex).toList());
// Traditional Java way
// _listImplementation.addAll(Arrays.stream(array).skip(arrayIndex).collect(Collectors.toList()));
}
public boolean remove(T item) {
sendPropertyChanged(item, ITEM_REMOVED);
return _listImplementation.remove(item);
}
public int count() {
return _listImplementation.size();
}
public boolean isReadOnly() {
return false;
}
public int indexOf(T item) {
return _listImplementation.indexOf(item);
}
public void insert(int index, T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(index, item);
}
public void removeAt(int index) {
_listImplementation.remove(index);
}
public T get(int index) {
return _listImplementation.get(index);
}
public void set(int index, T item) {
_listImplementation.set(index, item);
}
public void addObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.add(observer);
}
public void removeObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.remove(observer);
}
public void clearObserver() {
_changedObserverList.clear();
}
private void sendPropertyChanged(T item, String args) {
for (OnPropertyChangedObserver<T> observer : _changedObserverList) {
observer.onChanged(item, args);
}
}
public interface OnPropertyChangedObserver<T> {
void onChanged(T item, String args);
}
}
Other way is extends ArrayList instead _listImplementation. it can be provide more functionally. Personally, I prefer this way. Gist
Edit-1) Oh, i forget add args in OnPropertyChangeObserver.
Edit-2) Let Kotlin optimize this! Gist

Conditional calling using static factory method

This is my project structure. I'm trying to use a static factory function to check for an object and then perform some operations. I followed the this process.
Parent Class:
public abstract class Parent {
protected static Child1DTO ch1;
protected static Child2DTO ch2;
public Parent(Child1DTO ch1) {
this.ch1 = ch1;
}
public Parent(Child2DTO ch2) {
this.ch2 = ch2;
}
protected Parent() {
}
public static Child1DTO getCh1() {
return ch1;
}
public static Child2DTO getCh2() {
return ch2;
}
public static Class<?> childType(Object obj) {
if (obj instanceof Child1DTO) {
//do something
return Child1DTO.class;
} else if (obj instanceof Child2DTO) {
//do something
return Child2DTO.class;
}
return null;
}
}
Child1DTO Class:
public class Child1DTO extends Parent {
private String fName1;
private String lName1;
public String getfName1() {
return fName1;
}
public void setfName1(String fName1) {
this.fName1 = fName1;
}
public String getlName1() {
return lName1;
}
public void setlName1(String lName1) {
this.lName1 = lName1;
}
}
Child2DTO Class:
public class Child2DTO extends Parent{
private String fName2;
private String lName2;
public String getfName2() {
return fName2;
}
public void setfName2(String fName2) {
this.fName2 = fName2;
}
public String getlName2() {
return lName2;
}
public void setlName2(String lName2) {
this.lName2 = lName2;
}
}
Child Class:
public class Child extends Parent {
public Child(Child1DTO ch1) {
super(ch1);
}
public Child(Child2DTO ch2) {
super(ch2);
}
public static Child test(Object obj) {
if (obj instanceof Child1DTO) { //is this the correct way to check?
//do something
return new Child((Child1DTO) obj);
} else if (obj instanceof Child2DTO) {//is this the correct way to check?
//do something
return new Child((Child2DTO) obj);
}
return null;
}
public static void main(String args[]) {
if(childType(ch1).equals(ch1)){
//do something
}else if(childType(ch2).equals(ch2)){
//do something
}else{
System.out.println("Failed!");
}
}
}
EDIT:
Parent class has one Child class and two DTOs Child1DTO and Child2DTO.
Do I need to implement conditional check in Parent class or Child class?
How to achieve conditional check with constructors?

Java / JUnit - comparing two polynomial objects

I have a Java class called Term holding polynomials like below
public Term(int c, int e) throws NegativeExponent {
if (e < 0) throw new NegativeExponent();
coef = c;
expo = (coef == 0) ? 1 : e;
}
I also have an equals method in the same class like below
#Override
public boolean equals(Object obj) {
}
I am stuck with how to code how to compare these 2 Term objects
Within my JUnit test file I am using the test below to try and test the equals method
import static org.junit.Assert.*;
import org.junit.Test;
public class ConEqTest
{
private int min = Integer.MIN_VALUE;
private int max = Integer.MAX_VALUE;
#Test
public void eq01() throws TError { assertTrue(new Term(-10,0).equals(new Term(-10,0))); }
#Test
public void eq02() throws TError { assertTrue(new Term(0,0).equals(new Term(0,2))); }
What's wrong with
#Override
public boolean equals(Object obj) {
if (! (obj instanceof Term))
return false;
Term t = (Term)obj;
return coef == t.coef && expo == t.expo;
}
import static org.junit.Assert.*;
import org.junit.*;
#SuppressWarnings("serial") class NegativeExponentException extends Exception {}
class Term {
#Override public int hashCode() {
final int prime=31;
int result=1;
result=prime*result+coefficient;
result=prime*result+exponent;
return result;
}
#Override public boolean equals(Object obj) {
if(this==obj)
return true;
if(obj==null)
return false;
if(getClass()!=obj.getClass())
return false;
Term other=(Term)obj;
if(coefficient!=other.coefficient)
return false;
if(exponent!=other.exponent)
return false;
return true;
}
public Term(int c,int e) throws NegativeExponentException {
if(e<0)
throw new NegativeExponentException();
coefficient=c;
exponent=(coefficient==0)?1:e;
}
int coefficient,exponent;
}
public class So13408797TestCase {
#Test public void eq01() throws Exception {
assertTrue(new Term(-10,0).equals(new Term(-10,0)));
}
#Test public void eq02() throws Exception {
assertTrue(new Term(0,0).equals(new Term(0,2)));
}
private int min=Integer.MIN_VALUE;
private int max=Integer.MAX_VALUE;
}

Equivalent of C# ObservableCollection in Java

I was wondering if there is a data structure that acts like an OberservableCollection almost like in C# that is able to take a certain type.
ex:
In C# i am able to say..
ObservableCollection<Beer> Beer = new ObservableCollection<Beer>();
Beer.add("Bud"); <br>
Beer.add("Coors");
Assuming that the class Beer is made and we can change the alcohol content so that
Beer[1].content = 5;
I was wondering if anyone knows if there is such a data structure/s that work as well with Java.
I am a C# programmer, not much of a Java programmer so just wondering. Also, it has to be able to take in a custom type, not generic.
org.apache.commons.events.observable
Class ObservableCollection
Observable data structures (ObservableList, ObservableMap, etc) are included in Oracle Java 7u6+ as part of the JavaFX project. A corresponding library for OpenJDK is provided by the OpenJFX project.
Here is a tutorial on using JavaFX collections.
And some sample code for using a JavaFX observable list from the linked tutorial:
import java.util.List;
import java.util.ArrayList;
import javafx.collections.*;
public class CollectionsDemo {
public static void main(String[] args) {
// Use Java Collections to create the List.
List<String> list = new ArrayList<String>();
// Now add observability by wrapping it with ObservableList.
ObservableList<String> observableList = FXCollections.observableList(list);
observableList.addListener(new ListChangeListener() {
#Override public void onChanged(ListChangeListener.Change change) {
System.out.println("Detected a change! ");
}
});
// Changes to the observableList WILL be reported.
// This line will print out "Detected a change!"
observableList.add("item one");
// Changes to the underlying list will NOT be reported
// Nothing will be printed as a result of the next line.
list.add("item two");
System.out.println("Size: "+observableList.size());
}
}
If you want to Observe your lists, i.e. be notified when list changes, you can use Glazed Lists.
If you just want to modify objects stored in your lists, you can get your objects by using List.get(int index), or by iterating the list.
If you want to automatically create Beer objects when storing Strings into the list, you'll probably need to write your own simple list wrapper.
JavaFX now has ObservableList that match your needs, in the case that you don't want to depend on JavaFX - here is a class that I wrote a while ago that can be used instead.
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
/**
*
* #author bennyl
*/
public class ObservableList<T> implements List<T> {
private List<T> wrapped;
private LinkedList<Listener<T>> listeners = new LinkedList<>();
public ObservableList(List wrapped) {
this.wrapped = wrapped;
}
public void addListener(Listener l) {
listeners.add(l);
}
public void removeListener(Listener l) {
listeners.remove(l);
}
#Override
public int size() {
return wrapped.size();
}
#Override
public boolean isEmpty() {
return wrapped.isEmpty();
}
#Override
public boolean contains(Object o) {
return wrapped.contains(o);
}
#Override
public Iterator<T> iterator() {
final Iterator<T> iterator = wrapped.iterator();
return new Iterator<T>() {
T current = null;
#Override
public boolean hasNext() {
return iterator.hasNext();
}
#Override
public T next() {
return current = iterator.next();
}
#Override
public void remove() {
iterator.remove();
fireRemoved(current);
}
};
}
private void fireRemoved(T... items) {
fireRemoved(Arrays.asList(items));
}
#Override
public Object[] toArray() {
return wrapped.toArray();
}
#Override
public <T> T[] toArray(T[] a) {
return wrapped.toArray(a);
}
#Override
public boolean add(T e) {
if (wrapped.add(e)) {
fireAdded(e);
return true;
} else {
return false;
}
}
#Override
public boolean remove(Object o) {
if (wrapped.remove(o)) {
fireRemoved((T) o);
return true;
}
return false;
}
#Override
public boolean containsAll(Collection<?> c) {
return wrapped.containsAll(c);
}
#Override
public boolean addAll(Collection<? extends T> c) {
if (wrapped.addAll(c)) {
fireAdded(c);
return true;
}
return false;
}
#Override
public boolean addAll(int index, Collection<? extends T> c) {
if (wrapped.addAll(index, c)) {
fireAdded(c);
}
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
if (wrapped.removeAll(c)) {
fireRemoved((Collection<? extends T>) c);
return true;
}
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
if (wrapped.retainAll(c)) {
fireStracturalChange();
}
return false;
}
#Override
public void clear() {
wrapped.clear();
fireStracturalChange();
}
#Override
public boolean equals(Object o) {
return wrapped.equals(o);
}
#Override
public int hashCode() {
return wrapped.hashCode();
}
#Override
public T get(int index) {
return wrapped.get(index);
}
#Override
public T set(int index, T element) {
T old = wrapped.set(index, element);
fireRemoved(old);
fireAdded(element);
return old;
}
#Override
public void add(int index, T element) {
wrapped.add(index, element);
fireAdded(element);
}
#Override
public T remove(int index) {
T old = wrapped.remove(index);
fireRemoved(old);
return old;
}
#Override
public int indexOf(Object o) {
return wrapped.indexOf(o);
}
#Override
public int lastIndexOf(Object o) {
return wrapped.lastIndexOf(o);
}
#Override
public ListIterator<T> listIterator() {
return wrapped.listIterator();
}
#Override
public ListIterator<T> listIterator(int index) {
return wrapped.listIterator(index);
}
#Override
public List<T> subList(int fromIndex, int toIndex) {
return wrapped.subList(fromIndex, toIndex);
}
private void fireRemoved(Collection<? extends T> asList) {
for (Listener<T> l : listeners) {
l.onItemsRemoved(this, asList);
}
}
private void fireAdded(T... e) {
fireAdded(Arrays.asList(e));
}
private void fireAdded(Collection<? extends T> asList) {
for (Listener<T> l : listeners) {
l.onItemsAdded(this, asList);
}
}
private void fireStracturalChange() {
for (Listener<T> l : listeners) {
l.onStracturalChange(this);
}
}
public static interface Listener<T> {
void onItemsAdded(ObservableList<T> source, Collection<? extends T> items);
void onItemsRemoved(ObservableList<T> source, Collection<? extends T> items);
void onStracturalChange(ObservableList<T> source);
}
}
There isn't at least in Java Collections api
http://download-llnw.oracle.com/javase/1.5.0/docs/guide/collections/designfaq.html#27
You can create an wrapper or proxy
You can consider using the java.util.Observable class, here is an example :
public class Try extends Observable{
private static List<String> list = new ArrayList<String>();
private static Try observableObj = new Try();
public static List<String> getList(){
observableObj.setChanged();
observableObj.notifyObservers();
return list;
}
public static void main(String[] args) throws RemoteException {
Try2 observer1 = new Try2();
Try2 observer2 = new Try2();
observableObj.addObserver(observer1);
observableObj.addObserver(observer2);
System.out.println(getList().isEmpty());
}
}
class Try2 implements Observer{
#Override
public void update(Observable arg0, Object arg1) {
System.out.println(this.toString()+" has been notified");
}
}
In this way every time the ArrayList gets accessed the two observers get notified.
Sure, you can do this. If you had a class called Soda, you could do:
List<Soda> sodas = new ArrayList<Soda>();
sodas.add(new Soda("Coke"));
sodas.add(new Soda("Sprite"));
Then you could do
sodas.get(1).setSugar(255);

Categories