duplicate objects in list - networking

Im working on a programming project, I want to store some objects in a list but, but I cant get rid of the duplicates.
This is my object
nd = nodeAddress16=0x10,0x03, nodeAddress64=0x00,0x13,0xa2,0x00,0x40,0x6f,0x8d,0xfc, rssi=-47, nodeIdentifier=
[0x10,0x03]
The code is inside a thread, so the code is looping.
private void handleAtCommandResponse(XBeeResponse response) {
//TODO Implement your code here, to handle particular AT command responses, if desired.
System.out.println("NetworkNode: Received AT Response:"+((AtCommandResponse)response).getCommand());
if (response.getApiId() == ApiId.AT_RESPONSE) {
NodeDiscover nd = NodeDiscover.parse((AtCommandResponse)response);
System.out.println("Node discover response is: " + nd);
nodeDiscoverList.add(nd); //add to list, but gives duplicates of nd.
//add to list if not already in it
//if already in list replace that object with the new object
//duplicate objects are not allowed ==> only one object in the list can contain a specific address.
// Only addresses are static values, other values may change over time.
}
else {
log.debug("Ignoring unexpected response: " + response);
}
}

Without understanding the rest of the system to help determine why handleAtCommandResponse is being invoked multiple times with the same response, note that you can use a Set implementation like HashSet instead of a List to keep from storing duplicate objects. You may need NodeDiscover to implement hashCode() if it does not already.
A Setdoes not allow duplicate objects. If you call put() with the same object (rather, an object whose hashCode() is equal to that of another object in the set) twice, the first instance is replaced by the second.

Related

Java reflection to set static final field fails after previous reflection

In Java, it turns out that field accessors get cached, and using accessors has side-effects. For example:
class A {
private static final int FOO = 5;
}
Field f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
f.getInt(null); // succeeds
Field mf = Field.class.getDeclaredField("modifiers" );
mf.setAccessible(true);
f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.setInt(null, 6); // fails
whereas
class A {
private static final int FOO = 5;
}
Field mf = Field.class.getDeclaredField("modifiers" );
mf.setAccessible(true);
f = A.class.getDeclaredField("FOO");
f.setAccessible(true);
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.setInt(null, 6); // succeeds
Here's the relevant bit of the stack trace for the failure:
java.lang.IllegalAccessException: Can not set static final int field A.FOO to (int)6
at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)
at sun.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:100)
at sun.reflect.UnsafeQualifiedStaticIntegerFieldAccessorImpl.setInt(UnsafeQualifiedStaticIntegerFieldAccessorImpl.java:129)
at java.lang.reflect.Field.setInt(Field.java:949)
These two reflective accesses are of course happening in very different parts of my code base, and I don't really want to change the first to fix the second. Is there any way to change the second reflective access to ensure it succeeds in both cases?
I tried looking at the Field object, and it doesn't have any methods that seem like they would help. In the debugger, I noticed overrideFieldAccessor is set on the second Field returned in the first example and doesn't see the changes to the modifiers. I'm not sure what to do about it, though.
If it makes a difference, I'm using openjdk-8.
If you want the modifier hack (don't forget it is a total hack) to work, you need to change the modifiers private field before the first time you access the field.
So, before you do f.getInt(null);, you need to do:
mf.setInt(f, f.getModifiers() & ~Modifier.FINAL);
The reason is that only one internal FieldAccessor object is created for each field of a class (*), no matter how many different actual java.lang.reflect.Field objects you have. And the check for the final modifier is done once when it constructs the FieldAccessor implementation in the UnsafeFieldAccessorFactory.
When it is determined you can't access final static fields (because, the setAccessible override doesn't works but non-static final fields, but not for static final fields), it will keep failing for every subsequent reflection, even through a different Field object, because it keeps using the same FieldAccessor.
(*) barring synchronization issues; as the source code for Field mentions in a comment:
// NOTE that there is no synchronization used here. It is correct
(though not efficient) to generate more than one FieldAccessor for a
given Field.

How do I retrieve Firebase data in bulk for subsequent manipulation?

I'm transitioning from SQLite to Firebase and in doing so, I have a lot of pre-existing data that I need to set into different views.
Initial view: An alphabetical list (no duplicates), showing letters for only those resources that exist below it (meaning if there is no resource that starts with X, X should not show up at all).
Secondary view: Once you tap on a letter, it expands accordion style to reveal resources (no duplicates) that start with that letter.
My Firebase query is right in that I'm getting the correct data, but how do I use it? Ideally what I'd like to do is get all the topics, drop them in a TreeSet to eliminate duplicates and sort them automatically, then do the same thing but just getting the first letter. I cant modify a set, or an array, or a list from an inner class, but I can't access the same if I instantiate from inside either (and it doesn't matter because it gets called fresh for every single object so it's always a new set).
Is there a best practice I'm missing?
mDatabase = FirebaseDatabase.getInstance();
mRootRef = mDatabase.getReference();
mQuoteRef = mRootRef.child("quotes");
Query topicQuery = mQuoteRef.orderByChild("Topic");
topicQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
TreeSet<String> topicList = new TreeSet<>(); <--obv not right
TreeSet<String> firstLetterList = new TreeSet<>();
GetQuoteInfo quote = dataSnapshot.getValue(GetQuoteInfo.class);
if (quote.getTopic() != null) {
topicList.add(quote.getTopic());
firstLetterList.add(quote.getTopic().substring(0, 1));
}
}
}
magicalListThatContainsAllOfMyFirebaseDataThatICanNowManipulate;
When you retrieve data from a Firebase database, you retrieve it as a Map, and not as a Set. So in order to solve your problem, change the way in which you retrieve the data. Because Firebase is a NoSQL database, better said a JSON database, everything is structured as key and value. So, change the Set with a Map and your problem will be solved.
Hope it helps.

default Stream<E> stream() vs static<T> Stream<T> of(T t)

default Stream<E> stream() is added to Collection interface to support streams in Java 8. Similar functionality is supported by public static<T> Stream<T> of(T t) in Stream class. What different purpose is static of() method solving ?
The method stream() of the Collection interface can be called on an existing collection. Being an interface method, it can be overridden by actual collection implementations to return a Stream adapted to the specific collection type.
The standard collections of the JRE don’t take this opportunity, as the default implementation’s strategy of delegating to spliterator(), which is also an overridable method, suits their needs. But the documentation even mentions scenarios in which the collection should override stream():
This method should be overridden when the spliterator() method cannot return a spliterator that is IMMUTABLE, CONCURRENT, or late-binding.
In contrast, the static factory method(s) Stream.of(…) are designed for the case when you have a fixed number of elements without a specific collection. There is no need to create a temporary Collection when all you want is a single Stream over the elements you can enumerate.
Without collections of potentially different type, there is no need for overridable behavior, hence, a static factory method is sufficient.
Note that even if you don’t have a enumerable fixed number of elements, there is an optimized solution for the task of creating a single stream, when no reusable collection is needed:
Stream.Builder<MyType> builder=Stream.builder();
builder.add(A);
if(condition) builder.add(B);
builder.add(C);
builder.build()./* stream operations */
As far as I can tell, of is just an utility method to create Streams on the fly, without the need to wrap your elements inside a collection first.
Generally static factory methods as of are provided to skip the array creation because of var-args. For example java-9 immutable collections provide many overloads of these methods like:
Set.of()
Set.of(E)
Set.of(E e1, E e2)
.... so on until 11
Set.of(E... elem)
Even the description of those methods is:
While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls
Since there are only two methods in Stream:
Stream.of(T t)
Streamm.of(T ... values)
I consider that small utility methods that can create Streams from var-args.
But they still provide a method that creates a Stream with a single element (instead of leaving just the var-args method), so for a single element this is already optimized.
A interface can add static methods/default methods since jdk-8. and you can see some examples of applying patterns on interface in this question.
First, they are both calling StreamSupport.stream to create a stream.
// Collection.stream()
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
// Stream.of(E)
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
stream() added to Collection interface is a good example to applying Template-Method Pattern in interface by default methods. and you can see the source code that stream method call a method spliterator which implements by default in Collection interface.
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
AND class derived from Collection can be override spliterator implements different algorithm that will using highest performance algorithm instead. for example spliterator in ArrayList:
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
Finally, Stream.of() method is a good example to applying Factory Method in interface by static method. it's a factory method for create a stream from an object instance.
The other answers clearly explain the differences between Collection.stream and Stream.of, when to use one or the other, which design patterns are being applied, etc. #Holger goes even further and shows a sample usage of Stream.Builder, which I think is highly under-used.
Here I want to complement the other answers by showing a mixed usage of both Stream.of and Collection.stream methods. I hope that this example would be clear enough to show that even if both Stream.of and Collection.stream are completely different methods, they can also be used together to fulfil a more complex requirement.
Suppose you have N lists, all of them containing elements of the same type:
List<A> list1 = ...;
List<A> list2 = ...;
...
List<A> listN = ...;
And you want to create one stream with the elements of all lists.
You could create a new empty list and add the elements of all the lists into this new list:
int newListSize = list1.size() + list2.size() + ... + listN.size();
List<A> newList = new ArrayList<>(newListSize);
newList.addAll(list1);
newList.addAll(list2);
...
newList.addAll(listN);
Then, you could call stream() on this list and you would be done:
Stream<A> stream = newList.stream();
However, you would be creating an intermediate, pointless list, with the sole purpose of streaming the elements of the original list1, list2, ..., listN lists.
A much better approach is to use Stream.of:
Stream<A> stream = Stream.of(list1, list2, ..., listN)
.flatMap(Collection::stream);
This first creates a stream of lists by enumerating each one of them and then flat-maps this stream of lists into a stream of all lists' elements by means of the Stream.flatMap operation. Thus, Collection.stream is called when flat-mapping the original stream.

I want to pass predicate parameter to generic repository GetAll method in C# Asp.net

I want to filter my GetAll Repository function by passing predicate. I want to place a check that if country is not coming from ajax request, it should not be filtered and bring all records.
What i was wanting, see image
How i resolved it
I have resolved this problem by writing my own code, but i doubt it will be slower as it will first bring all the records. What is the perfect way, i am still confused.
string country = Request["country"]+"";
ICollection<Location> set = new LocationRepository().GetAll().ToList<Location>();
if (country != "")
set = set.Where(p => p.Country == country).ToList();
List<Location> list = set.OrderByDescending(p=>p.Id).Take(10).ToList();
I guess it will be something like the following
public void GetAll(Expression<Func<Location, bool>> exp)
{
....
}

multiple webrequests asynchronously in asp.net?

I have a page that needs to combine data from four different webrequests into a single list of items. Currently, I'm running these sequentially, appending to a single list, then binding that list to my repeater.
However, I would like to be able to call these four webrequests asynchronously so that they can run simultaneously and save load time. Unfortunately, all the async tutorials and articles I've seen deal with a single request, using the finished handler to continue processing.
How can I perform the four (this might even increase!) simultaneously, keeping in mind that each result has to be fed into a single list?
many thanks!
EDIT: simplified example of what i'm doing:
var itm1 = Serialize(GetItems(url1));
list.AddRange(itm1);
var itm2 = Serialize(GetItems(url2));
list.AddRange(itm2);
string GetItems(string url)
{
var webRequest = WebRequest.Create(url) as HttpWebRequest;
var response = webRequest.GetResponse() as HttpWebResponse;
string retval;
using (var sr = new StreamReader(response.GetResponseStream()))
{ retval = sr.ReadToEnd(); }
return retval;
}
This should be really simple since your final data depends on the result of all the four requests.
What you can do is create 4 async delegates each pointing to the appropriate web method. Do a BeginInvoke on all of them. And then use a WaitHandle to wait for all. There is no need to use call backs, in your case, as you do not want to continue while the web methods are being processed, but rather wait till all web methods finish execution.
Only after all web methods are executed, will the code after the wait statement execute. Here you can combine the 4 results.
Here's a sample code I developed for you:
class Program
{
delegate string DelegateCallWebMethod(string arg1, string arg2);
static void Main(string[] args)
{
// Create a delegate list to point to the 4 web methods
// If the web methods have different signatures you can put them in a common method and call web methods from within
// If that is not possible you can have an List of DelegateCallWebMethod
DelegateCallWebMethod del = new DelegateCallWebMethod(CallWebMethod);
// Create list of IAsyncResults and WaitHandles
List<IAsyncResult> results = new List<IAsyncResult>();
List<WaitHandle> waitHandles = new List<WaitHandle>();
// Call the web methods asynchronously and store the results and waithandles for future use
for (int counter = 0; counter < 4; )
{
IAsyncResult result = del.BeginInvoke("Method ", (++counter).ToString(), null, null);
results.Add(result);
waitHandles.Add(result.AsyncWaitHandle);
}
// Make sure that further processing is halted until all the web methods are executed
WaitHandle.WaitAll(waitHandles.ToArray());
// Get the web response
string webResponse = String.Empty;
foreach (IAsyncResult result in results)
{
DelegateCallWebMethod invokedDel = (result as AsyncResult).AsyncDelegate as DelegateCallWebMethod;
webResponse += invokedDel.EndInvoke(result);
}
}
// Web method or a class method that sends web requests
public static string CallWebMethod(string arg1, string arg2)
{
// Code that calls the web method and returns the result
return arg1 + " " + arg2 + " called\n";
}
}
How about launching each request on their own separate thread and then appending the results to the list?
you can test this following code:
Parallel.Invoke(() =>
{
//TODO run your requests...
});
You need reference Parallel extensions :
http://msdn.microsoft.com/en-us/concurrency/bb896007.aspx
#Josh: Regarding your question about sending 4 (potentially more) asynchronous requests and keeping track of the responses (for example to feed in a list). You can write 4 requests and 4 response handlers, but since you will potentially have more requests, you can write an asynchronous loop. A classic for loop is made of an init, a condition, and an increment. You can break down a classic for loop into a while loop and still be equivalent. Then you make the while loop into a recursive function. Now you can make it asynchronous. I put some sample scripts here at http://asynchronous.me/ . In your case, select the for loop in the options. If you want the requests to be sent in sequence, i.e. one request after the previous response (request1, response1, request2, response2, request3, response3, etc.) then choose Serial communication (i.e. sequential), but the code is a bit more intricate. On the other hand, if you don't care about the order in which the responses are received (random order), then choose Parallel communication (i.e concurrent), the code is more intuitive. In either case, each response will be associated with its corresponding request by an identifier (a simple integer) so you can keep track of them all. The site will give you a sample script. The samples are written in JavaScript but it's applicable to any language. Adapt the script to your language and coding preferences. With that script, your browser will send 4 requests asynchronously, and by the identifier you'll be able to keep track of which request the response corresponds to. Hope this helps. /Thibaud Lopez Schneider

Resources